Reputation: 15104
I'm trying to use the sort
command to sort integers in string separated by a space. For example 8 6 5 7 9 56 -20 - 10
. I receive the string on the standard output. I tried all of these but nothing works :
sort -t' '
sort -t ' '
sort -t " "
sort -t" "
sort -t=" "
Upvotes: 0
Views: 2116
Reputation: 254
echo "8 6 5 7 9 56 -20 - 10" | tr ' ' '\n' | sort -n
Sort can only sort lines.
Upvotes: 1
Reputation: 785058
You can first read string into an array with space as delimiter then use sort
with process substitution:
s='8 6 5 7 9 56 -20 - 10'
read -ra arr <<< "$s"
sort -n <(printf "%s\n" "${arr[@]}")
Output:
-20
-10
5
6
7
8
9
56
To store output in string again:
read -r str < <(sort -n <(printf "%s\n" "${arr[@]}") | tr '\n' ' ')
And check output:
declare -p str
declare -- str="-20 -10 5 6 7 8 9 56"
Upvotes: 1