Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stable sort in linux

I have a file

ksh$ cat test
b d
b c
a b
a a

I want to sort on first field but I want stable sort i.e. order of 2nd field should remain the same. I want output as:

a b
a a
b d
b c

If I try:

ksh$sort -k1 -s test   

I get

a a
a b
b c
b d

Please help,

Thanks

like image 312
xyz Avatar asked Dec 30 '10 11:12

xyz


People also ask

What is sort in Linux command?

The sort command is used in Linux to print the output of a file in given order. This command processes on your data (the content of the file or output of any command) and reorders it in the specified way, which helps us to read the data efficiently.

How do you sort data in Linux?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.

How do you sort from lowest to highest in Linux?

How to sort by number. To sort by number pass the -n option to sort . This will sort from lowest number to highest number and write the result to standard output. Suppose a file exists with a list of items of clothing that has a number at the start of the line and needs to be sorted numerically.


2 Answers

You forgot to constrain the key fields. By default it uses until the end of the line.

sort -k1,1 -s t.txt
like image 105
Ignacio Vazquez-Abrams Avatar answered Oct 07 '22 16:10

Ignacio Vazquez-Abrams


You must specify the end field:

sort -k1,1 -s test
like image 31
KARASZI István Avatar answered Oct 07 '22 16:10

KARASZI István