[本文出自天外归云的博客园]
在Linux shell中,如何将一个字符串转化为数组?
原文:https://www.golinuxcloud.com/bash-split-string-into-array-linux/
方法一:
myvar="string1 string2 string3" read -a myarray <<< $myvar echo "My array: ${myarray[@]}" echo "My array: ${myarray[0]}" echo "My array: ${myarray[1]}" echo "My array: ${myarray[2]}" echo "Number of elements in the array: ${#myarray[@]}"
方法二:
myvar="string1 string2 string3" myarray=($myvar) echo "My array: ${myarray[@]}" echo "My array: ${myarray[0]}" echo "My array: ${myarray[1]}" echo "My array: ${myarray[2]}" echo "Number of elements in the array: ${#myarray[@]}"
方法三:
myvar="string1,string2,string3" IFS="," read -a myarray <<< $myvar echo "My array: ${myarray[@]}" echo "My array: ${myarray[0]}" echo "My array: ${myarray[1]}" echo "My array: ${myarray[2]}" echo "Number of elements in the array: ${#myarray[@]}"
运行结果均为: