W7GVR
W7GVR

Reputation: 2000

bash: how to apply multiple commands to same file and concatenate outputs

Let's say that I want to aggregate the values by column on a tab separated file and preserve the header.

I could do:

  (head -n 1 <infile> && tail -n +2 | awk '{s+=$1} END {print s}' <infile>) > <outfile>

But let's say that I want the input to be coming from a pipe (e.g. I am doing the operation on a specific column).

How can I do that?

Does the one liner below work?

  (head -n 1 && tail -n +2 | awk '{s+=$1} END {print s}') <infile>  > <outfile>

If I want to sum just the k-th column, would the following work?

  cut -f<k> <infile> | (head -n 1 && tail -n +2 | awk '{s+=$1} END {print s}')  > <outfile>

How are these statements interpreted by bash?

Upvotes: 3

Views: 186

Answers (1)

Barmar
Barmar

Reputation: 781096

Do it all in awk, by testing NR

somecommand | awk 'NR == 1 { print; next } { s += $1 } END { print s }' > outfile

This prints the first line normally because of NR == 1, and then sums up the first column in the remaining lines.

Upvotes: 3

Related Questions