8

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?

1
  • I would have done something like: echo -e 'abc\nxyz\ncde' | perl -npe 's/(.)/ $1/g' | sort -k 3,3 | perl -npe 's/ //g' Commented Sep 12, 2012 at 8:11

5 Answers 5

11
$ 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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2
cat inputfile | perl -npe 's/(.)/ $1/g' | sort -k 3,3 | perl -npe 's/ //g'

Comments

1

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)} <>;'

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.