Sort part of a file

sorttext processing

How can I sort the file by the second column from the terminal. The content of the file is:

Nome     Note
------------
Mehdi    0
Sunday   20
Others   10
Shnou    5

Using sort -t' ' -nk2 is not giving me the right result. Also how can I ensure that the content of the file stay sorted?

Best Answer

I think what you're after is something like these:

Method #1: using head & tail

$ (head -n 2 sample.txt; tail -n +3 sample.txt | sort -t' ' -nk2) > a.tmp && mv a.tmp sample.txt

Nome     Note
------------
Mehdi    0
Shnou    5
Others   10
Sunday   20

This takes the first line of the text file, then tails everything after the first 2 lines which is then sorted.

Method #2: just using head

$ (head -n 2; sort -t' ' -nk2) < sample.txt > a.tmp && mv a.tmp sample.txt

Nome     Note
------------
Mehdi    0
Shnou    5
Others   10
Sunday   20

Takes the text file as input, displays just the first line, sort the rest.

It's typically not a good idea to edit files in place. It's possible, but better to use an intermediate file.

Method #3: Doing #2 without an intermediate file

Stealing the idea from @StephaneChazelas you could do the following using the "1<>" notation to open a file for reading & writing, and the improvements he suggested with the sort command.

$ (head -n 2; sort -nk2) < sample.txt 1<> sample.txt

Nome     Note
------------
Mehdi    0
Shnou    5
Others   10
Sunday   20
Related Question