SoFunction
Updated on 2025-03-09

Example of splitting strings in shell


For example, if you want to divide test="aaa,bbb,cc cc,dd dd", you can

Copy the codeThe code is as follows:

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

It's OK
Copy the codeThe code is as follows:

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

Then use
Copy the codeThe code is as follows:

for x in $arr; do
  echo $x
done

See the effect

Or more straightforward

Copy the codeThe code is as follows:

IFS=',' arr=($test)

This directly becomes a bash array. You can traverse this way:
Copy the codeThe code is as follows:

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

Or directly access by subscript:
Copy the codeThe code is as follows:

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