在 bash 中分割字符串

比如,要分割 test=”aaa,bbb,cc cc,dd dd”,可以这样

arr=$(echo $test|tr "," "\n")

还可以这样

OLD_IFS=$IFS
IFS=','
arr=$test
IFS=$OLD_IFS

然后用

for x in $arr; do
  echo $x
done

看看效果

或者更直接一点

IFS=',' arr=($test)

这样直接就变成了 bash 数组。可以这样遍历:

for x in ${arr[@]}; do
  echo $x
done

或者直接通过下标访问:

echo ${arr[0]}
echo ${arr[1]}

3 thoughts on “在 bash 中分割字符串

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.