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


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:


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?


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 | |

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 | |

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.