47

I've got a bunch of PDFs that I'm trying to append together, and I've got a program that, given a list of files, will append them to one PDF.

The issue I'm having is that piping the file names to sort does not produce the desired order. None of the flags of sort give me what I want either. I've got some examples below:

Desired sort order:

test1.pdf
test2.pdf
test10.pdf

Achieved sort order using sort:

test1.pdf
test10.pdf
test2.pdf

For more info on exactly what constitutes the sort order I desire, see:

http://msdn.microsoft.com/en-us/library/bb759947.aspx

jknielse
  • 701
  • 1
  • 6
  • 10

1 Answers1

67

Assuming you're using GNU sort, use the-V option:

   -V, --version-sort
          natural sort of (version) numbers within text

For your input, it'd produce:

test1.pdf
test2.pdf
test10.pdf
devnull
  • 118,548
  • 33
  • 236
  • 227
  • 14
    If you use `ls`, you can do `ls -1v`, which gives you this. – Sunny Patel Apr 08 '14 at 21:08
  • @LaughDonor Thanks. I don't happen to use `ls` much. – devnull Apr 08 '14 at 21:09
  • 1
    Unfortunately, -V does not work for the file names that I've got. They're of the form: sec2_pages12-20, sec2_pages21-30 etc... the ls option totally works though, thank you! – jknielse Apr 08 '14 at 21:30
  • I had to use "gsort" to get Gnu, otherwise no joy. The gsort -V option gave me exactly my desired sort on file names with 4 underscore-separated numbers e.g. a_b_V1_8_9 then a_b_V1_9_0 then a_b_V1_10_1. Using ls -1v didn't handle it. – Andrew Wolfe Feb 20 '15 at 15:47
  • @jknielse: I just tried your file name examples, and it worked with GNU sort version 8.23. – Craig McQueen Jul 06 '15 at 07:34
  • 2
    Unfortunately [BusyBox `sort`](http://www.busybox.net/downloads/BusyBox.html#sort) (typical on embedded Linux) doesn't support `-V` option. – Craig McQueen Jul 06 '15 at 07:35
  • 2
    For posterity, natural sort is not included with the `ls` that is part of FreeBSD or OSX as well. (I know, this question is about cygwin..) – ghoti Oct 12 '15 at 03:36
  • `sort -V` doesn't worked for me with hungarian characters. The solution was installing `natsort` and `PyICU`, then `natsort -lp` is perfect. – gabor.zed Jul 27 '22 at 18:17
  • works in git bash! – chiliNUT Sep 26 '22 at 17:09