How can I sort the string array in linux bash shel

2019-06-26 10:42发布

问题:

This question already has an answer here:

  • How to sort an array in Bash 15 answers

For instance, the array is

link2_pathname
link1_pathname
link3_pathname

How can I get the array like below.

link1_pathname
link2_pathname
link3_pathname

Thanks a lot in advance!

回答1:

pipe a loop to sort.

a=(l2 l3 l1)
b=($(for l in ${a[@]}; do echo $l; done | sort))

you probably need to watch out for the IFS when handling string values containing spaces.



回答2:

try this

var=( link2_pathname link1_pathname link3_pathname )

for arr in "${var[@]}"
do
    echo $arr
done | sort

new_var=( $(for arr in "${var[@]}" 
do
        echo $arr
done | sort) )


标签: linux bash shell