Bash: How to Sort Lines in File and Ignore First Line


Often you may want to use Bash to sort the lines in a file but ignore the first line, which is often a header row.

You can use the following syntax to do so:

awk 'NR<2{print;next}{print|"sort"}' players.txt

This particular example will sort the rows of the text file named players.txt and ignore the first row.

Here is how this syntax works:

  • The NR command in awk retrieves row numbers.
  • First, we use NR<2{print;next} to print all row numbers less than one. This simply prints the first row in the file.
  • Then, we use {print|”sort”|} to print all remaining rows in sorted order.

Note that if your file has multiple header rows then you can use NR<n where n+1 is the number of header rows.

The following example shows how to use this syntax in practice.

Example: Use Bash to Sort Lines in File and Ignore First Line

Suppose that we have the following file named players.txt that contains information about various basketball players:

Suppose that we would like to sort the file based on the team names in the first column.

Suppose we attempt to use the Bash sort command to do so:

sort players.txt

The following screenshot shows how to use this syntax in practice:

Notice that the rows are now sorted in ascending order based on team name, but the header row with the value “team” was also used for sorting.

We can instead use the following syntax to sort the rows based on team name while ignoring the first line:

awk 'NR<2{print;next}{print|"sort"}' players.txt

The following screenshot shows how to use this syntax in practice:

Bash sort ignore first line

Notice that the rows are now sorted based on team name, while ignoring the first line.

Also note that you could add the flag -r to sort in reverse order instead:

awk 'NR<2{print;next}{print|"sort -r"}' players.txt

The following screenshot shows how to use this syntax in practice:

Bash sort reverse ignore first line

The rows are now sorted in descending order based on team name, while ignoring the first line.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Characters in String
Bash: How to List All Files in Folder by Size

Leave a Reply