2

So I have a tab-separated input file that has blanks in a certain column like:

input_file:

A    B    C    D
1    12   34   545
34        12   56
23   10   15   67
31        99   100

Now, my goal is to add all such rows with blanks to my output_file like:

output_file:

34       12    56
31       99    100

So I use this command to achieve my result-

awk -F $'\t' '$2 == ""' input_file >> output_file

This works great if column "B" is always in position 2, however it won't work if it is in a different position. How do I address column "B" by its name in the awk command?

5

AFAIK there is no way to do this in awk short of iterating over the fields of the header and recording the index of the matching column:

awk -F '\t' 'NR==1{for(i=1;i<=NF;i++) if($i=="B") bi=i} $bi == ""' file.tsv

If you have access to Miller, you could filter by name directly ex.

mlr --tsv filter '$B == ""' file.tsv

or with utilities from the Python CSVKit:

csvgrep -t -c B -r "." -i file.tsv | csvformat -T
| improve this answer | |
3

You can process the first line to map the header names to column numbers:

awk -F'\t' '
  NR == 1 {for (i=1; i<=NF; i++) column[$i] = i}
  $(column["B"]) == ""
' input_file
| improve this answer | |
1

Another variant of awk command:

awk '!Bi{ FS="B"; $0=$0; Bi=1+gsub(/\t/,//,$1); FS="\t"; next} $Bi==""' infile
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.