1752577 Members
5377 Online
108788 Solutions
New Discussion юеВ

sorting column

 
SOLVED
Go to solution
Shivkumar
Super Advisor

sorting column

Dear Sirs,

I want to sort out column1 or column2 in ascending or descending order in the below output. This outputs are stored in a text file.

9.812 10023870 modifyUser managed2
7.741 7801930 modifyUser managed1
8.651 8900602 modifyUser managed2
11.94 12690787 login managed4
7.021 7127708 modifyUser managed4
6.009 6237126 migrateUser managed2

Can someone suggest combination of commands using grep, awk etc.

Thanks,
Shiv
5 REPLIES 5
Mel Burslan
Honored Contributor
Solution

Re: sorting column


for sorting string-value wise, i.e., 11.94 is smaller than 6.00, the first character is what is important for sorting

for column 1
sort -k 1 myfile > mysortedfile_col1

for column 2
sort -k 2 myfile > mysortedfile_col2

to sort for the numeric value:

sort -n -k 1 myfile > mysortedfile # sort acc to col 1 by numeric value

to reverse the sorting order

sort -rn -k 1 myfile > mysortedfile # sort acc to col 1 by numeric value in revrse order

hope this helps



________________________________
UNIX because I majored in cryptology...
Rajesh SB
Esteemed Contributor

Re: sorting column

Hi,

Assuming your data in file xyz.

Just do

# sort -k 2 < xyz|sort -k 1

11.94 12690787 login managed4
6.009 6237126 migrateUser managed2
7.021 7127708 modifyUser managed4
7.741 7801930 modifyUser managed1
8.651 8900602 modifyUser managed2
9.812 10023870 modifyUser managed2

If you want to sort in descending change the key option.

Regards,
Rajesh
Vibhor Kumar Agarwal
Esteemed Contributor

Re: sorting column

Use the -r option for sorting descending.

sort -r

Plus if you want unique options there is the -u tag.
Vibhor Kumar Agarwal
Raj D.
Honored Contributor

Re: sorting column

Shiv ,

# cat myfile | sort -k 2 > myfile2
# cat myfile2

will sort for column 2 , with follwoing output :

.812 10023870 modifyUser managed2
11.94 12690787 login managed4
6.009 6237126 migrateUser managed2
7.021 7127708 modifyUser managed4
7.741 7801930 modifyUser managed1
8.651 8900602 modifyUser managed2
$
---------------------------------------

Cheers,
Raj,
" If u think u can , If u think u cannot , - You are always Right . "
Arturo Galbiati
Esteemed Contributor

Re: sorting column

Hi Shiv,

sort -k 2 |sort -k 1 -r -o

This will sort by column 2 in asceding order and column 1 in descening order. Result in

HTH,
Art