Maryam
Maryam

Reputation: 45

How to sort a text file by column and keep the original order

I have a very large file of data with 15 columns. I need to sort all lines based on a specific column, say column 11. I am using this command in Linux:

sort -k11 -d myfile.txt > sortedfile

The problem is that the sort command does not preserve the original order of file. For instance, if I have something like this:

1 mh3
3 ygb
4 mh3

I need to have:

1 mh3
4 mh3
3 ygb

However, I may get:

4 mh3
1 mh3
3 ygb

Is there any option to keep the original order or any other commands that I can use?

Upvotes: 2

Views: 2731

Answers (1)

piokuc
piokuc

Reputation: 26194

Option -s is what you need (equivalent to --stable ):

sort -k11,11 -d -s myfile.txt > sortedfile

The option -k works with a range of fields, so you should probably add ,11 as I did above, otherwise the sorting will use keys spanning from column 11 to the end of line (default).

Upvotes: 10

Related Questions