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

前端 未结 4 734
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 15:46

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

c1 c2 c3 ..... c60

For example, delete columns be

相关标签:
4条回答
  • 2020-12-28 15:52

    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.

    0 讨论(0)
  • 2020-12-28 15:53

    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
    0 讨论(0)
  • 2020-12-28 15:55
    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
    
    0 讨论(0)
  • 2020-12-28 16:13

    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 讨论(0)
提交回复
热议问题