Sorting strings with numbers in Bash

hardcode57 picture hardcode57 · Jun 12, 2013 · Viewed 67.4k times · Source

I've often wanted to sort strings with numbers in them so that, when sorting e.g. abc_2, abc_1, abc_10 the result is abc_1, abc_2, abc_10. Every sort mechanism I've seen sorts as abc_1, abc_10, abc_2, that is character by character from the left.

Is there any efficient way to sort to get the result I want? The idea of looking at every character, determining if it's a numeral, building a substring out of subsequent numerals and sorting on that as a number is too appalling to contemplate in bash.

Has no bearded *nix guru implemented an alternative version of sort with a --sensible_numerical option?

Answer

Grzegorz Żur picture Grzegorz Żur · Jun 12, 2013

Execute this

sort -t _ -k 2 -g data.file
  • -t separator
  • -k key/column
  • -g general numeric sort