Reputation: 4159
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?
Upvotes: 8
Views: 6108
Reputation: 1
I had the same problem with lines that have one or more spaces before the line segment used as key. A field separator which is never present in the text to be sorted makes the whole line one field so you can use e.g.:
sort -n -t\| -k1.3,1.3 inputfile
Upvotes: 0
Reputation: 986
$ 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.
Upvotes: 11
Reputation: 3289
I would directly stick to perl and define a comparator
echo $content | perl -e 'print sort {substr($a,3,1) cmp substr($b,3,1)} <>;'
Upvotes: 1
Reputation: 2451
cat inputfile | perl -npe 's/(.)/ $1/g' | sort -k 3,3 | perl -npe 's/ //g'
Upvotes: 2
Reputation: 35246
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
Upvotes: 4