开发者

Deleting columns from a file with awk or from command line on linux

How can I delete some columns from a tab separated fields file with awk?

c1 c2 c3 ..... c60
开发者_运维知识库

For example, delete columns between 3 and 29 .


This is what the cut command is for:

cut -f1,2,30- inputfile

The default is tab. You can change that with the -d switch.


You can loop over all columns and filter out the ones you don't want:

awk '{for (i=1; i<=NF; i++) if (i<3 || i>29) printf $i " "; print""}' input.txt

where the NF gives you the total number of fields in a record.
For each column that meets the condition we print the column followed by a space " ".


EDIT: updated after remark from johnny:

awk -F 'FS' 'BEGIN{FS="\t"}{for (i=1; i<=NF-1; i++) if(i<3 || i>5) {printf $i FS};{print $NF}}' input.txt

this is improved in 2 ways:

  • keeps the original separators
  • does not append a separator at the end


awk '{for(z=3;z<=15;z++)$z="";$0=$0;$1=$1}1'

Input

c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19 c20 c21

Output

c1 c2 c16 c17 c18 c19 c20 c21


Perl 'splice' solution which does not add leading or trailing whitespace:

perl -lane 'splice @F,3,27; print join " ",@F' file

Produces output:

c1 c2 c30 c31
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜