1. 程式人生 > >Shell中將分隔符的字串轉為陣列的幾種方法

Shell中將分隔符的字串轉為陣列的幾種方法

要將字串列表轉變為陣列,只需要在前面加(),所以關鍵是將分隔符轉變為空格分隔,常用有下面幾種方法

  • 方法一: 藉助於{str//,/}來處理

[[email protected] ~]# str="ONE,TWO,THREE,FOUR"
[[email protected] ~]# arr=(${str//,/})
[[email protected] ~]# echo ${arr[@]}
ONE TWO THREE FOUR
  • 方法二: 藉助於tr命令來處理

[[email protected] ~]# str="ONE,TWO,THREE,FOUR"
[
[email protected]
~]# arr=(`echo $str | tr ',' ' '`) [[email protected] ~]# echo ${arr[@]} ONE TWO THREE FOUR
  • 方法三: 藉助於awk命令來處理

[[email protected] ~]# str="ONE,TWO,THREE,FOUR"
[[email protected] ~]# arr=($(echo $str | awk 'BEGIN{FS=",";OFS=" "} {print $1,$2,$3,$4}'))
[[email protected]
~]# echo ${str[*]}
  • 方法四: 藉助於IFS來處理分隔符

[[email protected] ~]# str="ONE,TWO,THREE,FOUR"
[[email protected] ~]# IFS=","
[[email protected] ~]# arr=(str)
[[email protected] ~]# echo ${str[@]}