remove specific fields from tab separated input file

132 Views Asked by At

input file#1 with tab separated fields:

one     two     three   four    five    six     four
one     two     three   four    five    six     four
one     two     three   four    five    six     four

case1: from each line, I need to remove all fields containing a string, for example four and get still single TAB separated remaining fields.

case2: I need to remove nth columns and leave still one TAB separation for the remaining fields on output, but here I get multiple TABs:

$ echo -e "one\ttwo\tthree\tfour\tfive\tsix\tfour\none\ttwo\tthree\tfour\tfive\tsix\tfour\none\ttwo\tthree\tfour\tfive\tsix\tfour"|awk -F"[\t]" '{$3="";$5=""}{print $0}' OFS='\t'
one     two             four            six     four
one     two             four            six     four
one     two             four            six     four

I can fix it by sending output via tr -s '\t', but how to modify awk to avoid the tr command?

1

There are 1 best solutions below

0
revo On BEST ANSWER

You could pipe output to sed, even though awk would be a working solution:

sed 's/\t*[^\t]*four[^\t]*//g'

Alternatively with awk:

awk -F\\t '{r = ""; for(i=1; i<=NF; i++) if($i !~ /four/) r = (r=="" ? "" : r FS) $i; print r}'