4

I'm trying to sort a file using the Sort command but its not working:

The file contains lines like:

photo1
photo11
photo12
photo13
photo17
photo18
photo19
photo2
photo22
photo23
photo25
photo26
photo27

I'm using the command, sort -k6 Photos so that it start sorting after the string "photo", can someone tell where I'm going wrong??

3
  • 1. You need to use -n or -g to sort numerically. 2. -k5 says to use the fifth whitespace-separated field as a key. I'm not sure sort can even handle starting in the middle of a field
    – Kevin
    Jun 29 '13 at 18:12
  • Ahh its 6 then, but it doesn't work as well
    – Noor
    Jun 29 '13 at 18:14
  • 3
    What do you mean by "it doesn't work"? It does work, only not as you expect. What is the output, and what do you expect?
    – Bernhard
    Jun 29 '13 at 19:50
5

Define the sort key with the start and stop character position of the key:

sort -nk1.6,1.8 file

See your friendly sort manpages.

4
  • Much cleaner than my solution.
    – user26112
    Jun 30 '13 at 2:07
  • what to do if the start of the number is not known, e.g. I want photo1 < photo2 < phot3 < photooo4 < photo5 Oct 3 '19 at 10:28
  • 1
    If the number doesn't begin at a fixed offset, inject a unique delimiter where the number begins to create a new field. Then sort using the delimiter and finally remove it: sed -E 's/([0-9]+)/:\1/' file | sort -t: -nk2,2 | tr -d ":"
    – JRFerguson
    Oct 4 '19 at 14:48
  • You can also add --debug to see if you're sorting by the right set of characters.
    – Ahmet
    Feb 23 '21 at 7:18
3

You have to specify a field separator.

sort -n -to -k3 Photos

-to tells sort to use o as the field separator. The numbers are in the third field (the first field contains ph and the second field contains t) so we use -k3. -n tells sort to sort numerically instead of alphabetically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.