Search code examples
shelltext-processing

How can sort a file on specific lines, preserving headers?


raw txt file contains these lines:

cat raw.txt
ID         DESCRIPTION
-----      --------------
2          item2
4          item4
1          item1
3          item3

How can reorder it by ID as following format?

ID         DESCRIPTION
-----      --------------
1          item1
2          item2
3          item3
4          item4

Tried sort -n:

cat  raw.txt |sort -n
-----      --------------
ID         DESCRIPTION
1          item1
2          item2
3          item3
4          item4

The dash line is ordered at the first line, how to make it the second line?


Solution

  • You was in the right direction, but the issue to resolve is to sort only a part of the file, so a simple pipe approach to address the issue is:

    $ head -n2 raw.txt; awk 'NR>2' raw.txt | sort -n 
    ID         DESCRIPTION
    -----      --------------
    1          item1
    2          item2
    3          item3
    4          item4
    

    to edit the file in place:

    $ { head -n2 raw.txt; awk 'NR>2' raw.txt | sort -n; } | sponge raw.txt
    

    man sponge

    sponge - soak up standard input and write to a file


    apt install moreutils on Debian/Ubuntu and derivatives