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?
To sort by number pass the -n option to sort . This will sort from lowest number to highest number and write the result to standard output. Suppose a file exists with a list of items of clothing that has a number at the start of the line and needs to be sorted numerically.
Bash Sort Files Alphabetically By default, the ls command lists files in ascending order. To reverse the sorting order, pass the -r flag to the ls -l command, like this: ls -lr . Passing the -r flag to the ls -l command applies to other examples in this tutorial.
If you want to handle embedded newlines, you can roll your own readarray. For example: sorted=(); while read -d $'\0' elem; do sorted[${#sorted[@]}]=$elem; done < <(printf '%s\0' "${array[@]}" | sort -z) . This also works in you are using bash v3 instead of bash v4, because readarray isn't available in bash v3.
-r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. Example: The input file is the same as mentioned above.
Execute this
sort -t _ -k 2 -g data.file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With