In bash, how to sort strings with numbers in them?
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
Related videos on Youtube
ngm
Updated on September 17, 2022Comments
-
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 followingpdftk `ls *.pdf | sort -n` cat output output.pdf
but that doesn't work as my sorting is wrong.
-
ngm over 14 yearsAha, nice approach! It does indeed do what I what, thanks.
-
Dennis Williamson over 14 yearsPerhaps a little more succinctly:
pdftk cwcch{{1..9},{10..18}}.pdf ...
-
quack quixote over 14 yearsgood tip, added in. is that a standard Bourne shell expansion syntax or a
bash
extension? -
Xen2050 over 8 yearsDoes this one liner work on the
tmp
file? Any output to paste into the answer? -
Aguevara over 8 yearsYes. I included the output in my OP under the edit section.
-
panmari over 8 yearsExcerpt of relevant entry in sort man page:
-V, --version-sort natural sort of (version) numbers within text
-
eventhorizon almost 6 yearsThis 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 almost 5 yearsThis is the most simple solution, it needs more upvotes folks!