In bash, how to sort strings with numbers in them?

53,806

Solution 1

Something like this might do what you want, though it takes a slightly different approach:

pdftk $(for n in {1..18}; do echo cwcch$n.pdf; done) cat output output.pdf

Solution 2

Your sort may have the ability to do this for you:

sort --version-sort

Solution 3

For this particular example you could also do this:

ls *.pdf | sort -k2 -th -n

That is, sort numerically (-n) on the second field (-k2) using 'h' as the field separator (-th).

Solution 4

You can use the -v option in GNU ls: natural sort of (version) numbers within text.

ls -1v cwcch*

This does not work with BSD ls (e.g. on OS X), where the -v option has a different meaning.

Solution 5

Here's a method just using sort:

ls | sort -k1.6n
Share:
53,806

Related videos on Youtube

ngm
Author by

ngm

Updated on September 17, 2022

Comments

  • ngm
    ngm over 1 year

    If I have these files in a directory

    cwcch10.pdf
    cwcch11.pdf
    cwcch12.pdf
    cwcch13.pdf
    cwcch14.pdf
    cwcch15.pdf
    cwcch16.pdf
    cwcch17.pdf
    cwcch18.pdf
    cwcch1.pdf
    cwcch2.pdf
    cwcch3.pdf
    cwcch4.pdf
    cwcch5.pdf
    cwcch6.pdf
    cwcch7.pdf
    cwcch8.pdf
    cwcch9.pdf
    

    how can I list them in Bash so that they are in ascending numeric order based on the number part of the string. So the resulting order is cwcch1.pdf, cwcch2.pdf, ..., cwcch9.pdf, cwcch10.pdf, etc.

    What I'm ultimately trying to do is concatenate the pdfs with pdftk with something like the following

    pdftk `ls *.pdf | sort -n` cat output output.pdf
    

    but that doesn't work as my sorting is wrong.

  • ngm
    ngm over 14 years
    Aha, nice approach! It does indeed do what I what, thanks.
  • Dennis Williamson
    Dennis Williamson over 14 years
    Perhaps a little more succinctly: pdftk cwcch{{1..9},{10..18}}.pdf ...
  • quack quixote
    quack quixote over 14 years
    good tip, added in. is that a standard Bourne shell expansion syntax or a bash extension?
  • Xen2050
    Xen2050 over 8 years
    Does this one liner work on the tmp file? Any output to paste into the answer?
  • Aguevara
    Aguevara over 8 years
    Yes. I included the output in my OP under the edit section.
  • panmari
    panmari over 8 years
    Excerpt of relevant entry in sort man page: -V, --version-sort natural sort of (version) numbers within text
  • eventhorizon
    eventhorizon almost 6 years
    This is what you need. But if your sort does not supply this option take a look at this post: stackoverflow.com/a/4495368/1240018
  • davidparks21
    davidparks21 almost 5 years
    This is the most simple solution, it needs more upvotes folks!