delete last 3 columns from a file

2019-02-25 08:34发布

I have a text file with 6 columns. How can I delete the last three columns from this file?

c1  c2  c3  c4  c5   c6

desired output

c1  c2  c3

标签: shell unix sed awk
6条回答
相关推荐>>
2楼-- · 2019-02-25 08:47

If spacing are not important, here is how to delete last 3 fields.

awk '{NF-=3}1' file
c1 c2 c3

You could even use

awk 'NF-=3' file

But its not as robust as the first example.

查看更多
Viruses.
3楼-- · 2019-02-25 08:47

To delete the last N columns in each row, you can simply reduce NF (the number of fields) by that amount, taking into account the special case where there aren't enough columns to delete):

pax> echo c1 c2 c3 c4 c5 c6 | awk -vN=3 '{if(NF<N){NF=0}else{NF-=N}print}'
c1 c2 c3

Keep in mind that awk is primarily a tool for processing columns of data. You'll notice that my output has a single space between fields since column-based processing doesn't usually care about the type of whitespace.

If spacing is important (ie, you want to preserve, for example, the number of spaces between columns), you should probably look into another tool.

查看更多
神经病院院长
4楼-- · 2019-02-25 08:50

awk '{print $1 " " $2 " " $3}' filename > filename.new

查看更多
Explosion°爆炸
5楼-- · 2019-02-25 08:53

You can use @paxdiablo's awk to reduce the value of NF

alternatively you can use sed

sed 's/\([ \t]\+[^ \t]*\)\{3\}$//' your_file

If you are on Linux, GNU sed provides -r

sed -r 's/([ \t]+[^ \t]*){3}$//' your_file
查看更多
一纸荒年 Trace。
6楼-- · 2019-02-25 09:08

Pure bash (if spacing is not important):

tr -s ' ' < file | rev | cut -d' ' -f4- | rev

use cut -d' ' -f5- if there are trailing space(s), or trim trailing spaces before these.

But I do like the Jotne/paxdiablo's awk NF solution much better.

查看更多
姐就是有狂的资本
7楼-- · 2019-02-25 09:14

If columns are separated by single space:

cut -d " " -f1-3 file

If columns are separated by multiple space:

tr -s " " file | cut -d " " -f1-3

If columns are separated by tab:

cut -f1-3 file
查看更多
登录 后发表回答