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?

3 Answers 3

6

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

Another variant of awk command:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .