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

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.


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.