Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix sort on column without separator

Tags:

unix

sorting

I'd like to sort a file content with a Unix script depending on a particular column :

ex : sort the following file on the 3rd column :

ax5aa 
aa3ya 
fg7ds 
pp0dd 
aa1bb

would result as

pp0dd
aa1bb
aa3ya
ax5aa
fg7ds

I have tried sort -k 3,3, but it just sort on the 3d group of word (separator=SPACE).

Is there any way to have unix sort behave the way I like, or should I use another tool?

like image 963
chburd Avatar asked Sep 12 '12 08:09

chburd


2 Answers

$ sort --key=1.3,1.3 inputfile
pp0dd
aa1bb
aa3ya
ax5aa
fg7ds

man page of sort:

[...]

-k, --key=POS1[,POS2]

start a key at POS1 (origin 1), end it at POS2 (default end of line)

[...]

POS is F[.C][OPTS], where F is the field number and C the character position in the field; both are origin 1. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

With --key=1.3,1.3, you said that there only one field (the entire line) and that you're comparing the third character position of this field.

like image 178
Franck Avatar answered Sep 24 '22 06:09

Franck


use sed to create the columns before sorting

$ echo "ax5aa 
aa3ya 
fg7ds 
pp0dd 
aa1bb" | sed 's/\(.\)/\1 /g' | sort -t ' ' -k3,3 | tr -d ' '

pp0dd
aa1bb
aa3ya
ax5aa
fg7ds
like image 41
Pierre Avatar answered Sep 24 '22 06:09

Pierre