显示除最后一个字段以外的所有字段 [英] Display all fields except the last
问题描述
我有一个如下所示的文件
I have a file as show below
1.2.3.4.ask
sanma.nam.sam
c.d.b.test
我想从每行中删除最后一个字段,分隔符为.
,并且字段数不是恒定的.
I want to remove the last field from each line, the delimiter is .
and the number of fields are not constant.
任何人都可以通过awk
或sed
帮助我找出解决方案.我不能在这里使用perl
.
Can anybody help me with an awk
or sed
to find out the solution. I can't use perl
here.
推荐答案
这两个sed
和awk
解决方案的工作均与字段数无关.
Both these sed
and awk
solutions work independent of the number of fields.
使用sed
:
$ sed -r 's/(.*)\..*/\1/' file
1.2.3.4
sanma.nam
c.d.b
注意:-r
是扩展正则表达式的标志,它可能是-E
,因此请使用man sed
进行检查.如果您的sed
版本对此没有标记,则只需跳过方括号:
Note: -r
is the flag for extended regexp, it could be -E
so check with man sed
. If your version of sed
doesn't have a flag for this then just escape the brackets:
sed 's/\(.*\)\..*/\1/' file
1.2.3.4
sanma.nam
c.d.b
sed
解决方案对最后一个.
进行贪心匹配并捕获之前的所有内容,它仅用匹配的部分(n-1
字段)替换整行.如果要将更改存储回文件中,请使用-i
选项.
The sed
solution is doing a greedy match up to the last .
and capturing everything before it, it replaces the whole line with only the matched part (n-1
fields). Use the -i
option if you want the changes to be stored back to the files.
使用awk
:
$ awk 'BEGIN{FS=OFS="."}{NF--; print}' file
1.2.3.4
sanma.nam
c.d.b
awk
解决方案仅打印n-1
字段,即可使用重定向将更改存储回文件:
The awk
solution just simply prints n-1
fields, to store the changes back to the file use redirection:
$ awk 'BEGIN{FS=OFS="."}{NF--; print}' file > tmp && mv tmp file
这篇关于显示除最后一个字段以外的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!