Sorting strings with numbers in Bash [duplicate]

Solution 1:

Execute this

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

Solution 2:

I think this is a GNU extension to sort, but you're looking for the --version-sort (or -V) option:

$ printf "prefix%d\n" $(seq 10 -3 1)
prefix10
prefix7
prefix4
prefix1

$ printf "prefix%d\n" $(seq 10 -3 1) | sort
prefix1
prefix10
prefix4
prefix7

$ printf "prefix%d\n" $(seq 10 -3 1) | sort --version-sort
prefix1
prefix4
prefix7
prefix10

https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html