How would I sort a CSV file by the first column, where the first column a lowercase string, ignoring header line?
Asked
Active
Viewed 1.6k times
8
-
1Related: http://unix.stackexchange.com/q/11856/117549 – Jeff Schaller Feb 15 '17 at 03:42
-
1Also: http://unix.stackexchange.com/a/170601/117549 – Jeff Schaller Feb 15 '17 at 03:43
3 Answers
11
sort
does not have an option to exclude header. You can remove the header using:
tail -n+2 yourfile | sort
This tail syntax gets yourfile
from second line up to the end of the file.
Of course the results of sort
will not include the header.
You can isolate the header with command head -n1 yourfile
which will print only the first line of your file (your header).
To combine them together you can run:
head -n1 yourfile && tail -n+2 yourfile | sort

Michael Mior
- 240

George Vasiliou
- 7,913
-
1Brilliant, thanks. Worked a charm. There's a typo on the first line, yourfile and youfile, in case someone else wants to use it in the future. – normannen Feb 15 '17 at 16:02
10
I assume you want to keep the header: redirect the contents of the file into a grouped construct:
{
# grab the header and print it untouched
IFS= read -r header
echo "$header"
# now process the rest of the input
sort
} < file.csv

glenn jackman
- 85,964
5
Using csvkit
:
$ csvsort -c 1 file.csv
or just
$ csvsort file.csv
The difference is that the first command will only use the first column, while the second will use all (like sort
does).
The csvkit
tools assumes that the input CSV file has a header line as its first line. Use -H
if the file has no header.

Kusalananda
- 333,661
-
3Tip:
csvkit
can be installed using Homebrew withbrew install csvkit
. Handy! – Joshua Pinter Jan 11 '19 at 05:20 -
-
1@PauloSergioSchlogl
csvsort
can not sort files in place. But it's easy to redirect to a temporary file and then replace the original with that. – Kusalananda May 19 '22 at 10:44