Bash script: how to skip a header line when sorting a text or csv file, while retaining it in the output

158 Views Asked by At

(Adapted from this: Join Manual, Header lines).

I am sorting a file called file1 with this content:

Name   Age
Charlie 34
Alice   25

If I just write:

sort -k2b,2 file1

I get:

Alice   25
Charlie 34
Name   Age

I can exclude the header from the sort like so:

head -1 file1 ;(sed -n '2,$p' file1|sort -k2b,2)

But the example in the gnu manual is this:

( sed -u 1q ; sort -k2b,2 ) < file1

Why does that work?

I would think that I would get this instead from the command-line:

Name   Age
Alice   25
Charlie 34
Name   Age

The sed consumes the first line of stdin, then the sort consumes the rest?

1

There are 1 best solutions below

0
Cole Tierney On

You could have sed print the header, then sort the rest.

sed -n '1p' file1; sort <(sed '1d' file1)
Name   Age
Alice   25
Charlie 34