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

前端 未结 4 742
伪装坚强ぢ
伪装坚强ぢ 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: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

提交回复
热议问题