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 Commented Jun 29, 2013 at 18:12
  • Ahh its 6 then, but it doesn't work as well Commented Jun 29, 2013 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? Commented Jun 29, 2013 at 19:50

2 Answers 2

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. Commented Jun 30, 2013 at 2:07
  • what to do if the start of the number is not known, e.g. I want photo1 < photo2 < phot3 < photooo4 < photo5 Commented Oct 3, 2019 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 ":" Commented Oct 4, 2019 at 14:48
  • You can also add --debug to see if you're sorting by the right set of characters. Commented Feb 23, 2021 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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.