user3285713
user3285713

Reputation: 151

How to sort a text file numerically and then store the results in the same text file?

I have tried sort -n test.text > test.txt. However, this leaves me with an empty text file. What is going on here and what can I do to solve this problem?

Upvotes: 0

Views: 110

Answers (2)

SantanuMajumdar
SantanuMajumdar

Reputation: 916

Sort does not sort the file in-place. It outputs a sorted copy instead.

You need sort -n -k 4 out.txt > sorted-out.txt.

Edit: To get the order you want you have to sort the file with the numbers read in reverse. This does it:

cut -d' ' -f4 out.txt | rev | paste - out.txt | sort -k1 -n | cut -f2- > sorted-out.txt

For more learning -

sort -nk4 file

-n for numerical sort

-k for providing key

or add -r option for reverse sorting

sort -nrk4 file

Upvotes: 1

Breno Leitão
Breno Leitão

Reputation: 3677

It is because you are reading and writing to the same file. You can't do that. You can try something a temporary file, as mktemp or even something as:

sort -n test.text > test1.txt
mv test1.txt test

For sort, you can also do the following:

sort -n test.text -o test.text

Upvotes: 0

Related Questions