Home » Questions » Computers [ Ask a new question ]

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

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

If I have these files in a directory

Asked by: Guest | Views: 194
Total answers/comments: 4
Guest [Entry]

"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"
Guest [Entry]

"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)."
Guest [Entry]

"Here's a method just using sort:

ls | sort -k1.6n"
Guest [Entry]

"Sort -g is used to sort numbers in ascending order.

anthony@mtt3:~$ sort --help | egrep ""\-g""
-g, --general-numeric-sort compare according to general numerical value

The following one liner iterates over a file with the names of the PDF files and grabs the numbers only with egrep -o and uses sort -g to sort the numbers in ascending order. Then it feeds these numbers to sed and plugs them in. Then rids the output of duplicates with uniq.

In place of uniq, you can also use awk:

awk '!x[$0]++'

The above is equivalent to uniq.

What you're looking for is this one liner:

for i in `cat tmp | egrep -o ""[0-9]*"" | sort -g`; do cat tmp | sed ""s/\(^[a-z]*\)\([0-9]*\)\(\.pdf\)/\1$i\3/g"" | uniq; done

Contents of tmp:

anthony@mtt3:~$ cat tmp
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

EDIT:

Output of command:

anthony@mtt3:~$ for i in `cat tmp | egrep -o ""[0-9]*"" | sort -g`; do cat tmp | sed ""s/\(^[a-z]*\)\([0-9]*\)\(\.pdf\)/\1$i\3/g"" | uniq; done

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