Unix: How to sort a dat file and keep original line numbers

2.2k views Asked by At

I have a large data file containing over a thousand entries. I would like to sort them but maintain the original line numbers. For instance,

1:100
2:120
3:10
4:59

Where the first number is the line number, not saved in the data file, separated by a colon from the real number. I would like to sort it and keep the line numbers bound to their original lines, with an output of:

2:120
1:100
4:59
3:10

If possible, I would like to do this without creating another file, and numbering them by hand is not an option for the data size I'm using.

1

There are 1 answers

2
Simon On

Given a file test.dat:

100
120
10
59

... the command:

$ cat -n test.dat | sort --key=2 -nr
     2  120
     1  100
     4  59
     3  10

... gives the output that you seem to be looking for (though with the fields delimited by tabs, which is easily changed if necessary):

$ cat -n test.dat | sort --key=2 -nr | sed -e's/\t/:/'
     2:120
     1:100
     4:59
     3:10