Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix skip-header bash function

Tags:

bash

Somewhere on stackoverflow I got a bash function called "body" which would echo the header (first line) of a file, and pass the body (rest of the lines) along to stdout. This has been very useful for me to work with files that have headers.

Example:

file.csv:

field1,field2
a,2
b,1

Commands:

$ sort -k2,2 -nr file.csv -t,
a,2
b,1
field1,field2

$ cat file.csv | body sort -nr -t, -k2,2
field1,field2
a,2
b,1

Not a great example, but it shows the header staying on top.

Minutes of Googling and searching stackoverflow have revealed nothing.

Can anyone find or reconstruct such a function?

like image 613
dfrankow Avatar asked May 13 '26 19:05

dfrankow


1 Answers

Here is one way that would allow you to grab the header... and then grab the rest of the csv file, and sort (or whatever else you want to do with the data,) and it all gets saved to the outpipe.

head -1 file.csv > outpipe | tail -n+2 file.csv | sort >> outpipe

Edit:

If that approach doesn't work for you, you could always try something like the answers in this previous discussion.

like image 197
summea Avatar answered May 16 '26 10:05

summea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!