1833792 Members
2530 Online
110063 Solutions
New Discussion

Sorting problem

 
Marko_3
Contributor

Sorting problem

Dear all

I would like to ask a question on 'sort' in Unix.

I have a file which contains the following records:

18,0001,abc,xyz
19,0001,wxy,ghi

I would like to sort by the second field in the record. If more than one records are found with the same second field, then I only want the first record. That is to say, in the example above, I only want to return
18,0001,abc,xyz

Another question,
How do I sort using more than one fields in the record, for example
20,123,abc,def
21,246,xyz,ijk
I would like to sort by the second and last field. How do I do do that using the 'sort' command?

Many thanks


3 REPLIES 3
Wieslaw Krajewski
Honored Contributor

Re: Sorting problem

Hi,

Try

sort -u -t, -k2,2 file_to_be_sorted

Rgds
Permanent training makes master
vtpaulson
Frequent Advisor

Re: Sorting problem

Hi,

This script will sort out your 'filename' in terms of 2nd field and keep it in newfile. It will keep only the first line of similar content as you required....

cat filename | awk'FS = "," {print $2}' | sort -n > tempfile
for i in 'tmpfile'
do
grep $i filename | head -1 >> newfile
done

Regarding sort in 2 fields, you have to write similar kind of script......

Hope it helps.....
Vincent Stedema
Esteemed Contributor

Re: Sorting problem

Uhmm,

let's give this a try:

cat your_file | sort -t, -n +1 -2 | awk -F, 'BEGIN {prev="" } {if (prev!=$2) {print $0; prev=$2} else {prev=$2}}' -

About the double sort: this should work to a certain extent with a double range declaration. But I'm not sure if the second sort really does a dictionary sort or converts the chars to an ascii value and sorts them numerically.

E.g.:

cat your_file | sort -t, -n +1 -2 -d +4 -5

Regards,

Vincent