Achal Neupane
Achal Neupane

Reputation: 5719

How to include tsv/csv header in bash script output

I have thousands of .tsv files where I am extracting the rows where column 2 is equal column 6.

I can use the below bash script, but I could not append column names (header) in the output.

What is the way to include header?

for x in *.tsv; do
   awk '$2==$6' <"$x" >"$x.tmp"
   mv "$x.tmp" "$x"
done

Upvotes: 1

Views: 437

Answers (1)

fedorqui
fedorqui

Reputation: 289525

If you want to print based on two conditions, say so:

awk 'FNR==1 || $2==$6' file

This will print those lines that either of these:

  • match the $2==$6 condition.
  • are the first line.

Also, note you don't need to loop with bash, awk can do it:

awk '(FNR==1 || $2==$6) {print > FILENAME".bk"}' *.tsv

Upvotes: 2

Related Questions