How to sort strings that contain a common prefix and suffix numerically from Bash? How to sort strings that contain a common prefix and suffix numerically from Bash? bash bash

How to sort strings that contain a common prefix and suffix numerically from Bash?


Use ls -lv

From the man page:

-v     natural sort of (version) numbers within text


Try the following:

sort -t '_' -k 2n
  • -t '_' (sets the delimiter to the underscore character)
  • -k 2n (sorts by the second column using numeric ordering)

DEMO.


If available, simply use sort -V. This is a sort for version numbers, but works well as a "natural sort" option.

$ ff=$( echo some.string_{100,101,102,23,24,25}_with_numbers.in-it.txt )

Without sort:

$ for f in $ff ; do echo $f ; donesome.string_100_with_numbers.in-it.txtsome.string_101_with_numbers.in-it.txtsome.string_102_with_numbers.in-it.txtsome.string_23_with_numbers.in-it.txtsome.string_24_with_numbers.in-it.txtsome.string_25_with_numbers.in-it.txt

With sort -V:

$ for f in $ff ; do echo $f ; done | sort -Vsome.string_23_with_numbers.in-it.txtsome.string_24_with_numbers.in-it.txtsome.string_25_with_numbers.in-it.txtsome.string_100_with_numbers.in-it.txtsome.string_101_with_numbers.in-it.txtsome.string_102_with_numbers.in-it.txt