Issue
Say I have an array of strings Names, such as,
_billy_2 _bobby_1 _william_3
I am trying to order them descending by their numeric value,
i'am doing so by using something like:
sortNames=($( printf '%s\n' "${names[@]}" | sort -k3 -t'_' -r))
However, this works until I have an array such as:
_billy_115 _bobby_3 _william_4
This will print out:
_william_4 _bobby_3 _billy_115
Rather than:
_billy_115 _william_4 _bobby_3
Any ideas as to why?
Solution
Using sed
to seperate each string onto a new line
$ sed 's/[^ ]*/&\n/g' input_file | rev | sort -r | rev | xargs
_william_3 _billy_2 _bobby_1
$ sed 's/[^ ]*/&\n/g'
- This will match up to the final digit for each string, return the match and add a new line
rev
- Reverse so the sort can be carried on the numbers
sort -r
- Reverse sort
Answered By - HatLess