Thursday, February 25, 2010

bash: split string to array

There are few possible ways of splitting a string with delimiter-separated values to an array in Bash. Here I present five of them.

1. Using tr command

#!/bin/bash
STR="123,456,567 5,343"
STR_ARRAY=(`echo $STR | tr "," "\n"`)
for x in "${STR_ARRAY[@]}"
do
echo "> [$x]"
done
Output:> [123]
> [456]
> [567]
> [5]
> [343]
This method will produce incorrect array due to space in "567 5", but it works fine if there are no spaces in the $STR variable.

2. Using IFS (Internal Field Separator) variable

#!/bin/bash
STR="123,456,567 5,343"
OLD_IFS="$IFS"
IFS=","
STR_ARRAY=( $STR )
IFS="$OLD_IFS"
for x in "${STR_ARRAY[@]}"
do
echo "> [$x]"
done
Output:> [123]
> [456]
> [567 5]
> [343]
This method works fine even if there are spaces.

3. Using read command

#!/bin/bash
STR="123,456,567 5,343"
IFS="," read -ra STR_ARRAY <<< "$STR"
for x in "${STR_ARRAY[@]}"
do
echo "> [$x]"
done
Output:> [123]
> [456]
> [567 5]
> [343]
This method also works fine even though there are spaces in the $STR variable.

4. Using sed command

#!/bin/bash
STR="123,456,567 5,343"
STR_ARRAY=(`echo $STR | sed -e 's/,/\n/g'`)
for x in "${STR_ARRAY[@]}"
do
echo "> [$x]"
done
Output:> [123]
> [456]
> [567]
> [5]
> [343]
This method will also produce incorrect array due to space in "567 5", but it works fine if there are no spaces in the $STR variable.

5. Using set command

#!/bin/bash
STR="123,456,567 5,343"
set -- "$STR"
IFS=","; declare -a STR_ARRAY=($*)
for x in "${STR_ARRAY[@]}"
do
echo "> [$x]"
done
Output:> [123]
> [456]
> [567 5]
> [343]
This method also works fine.

References

This post was mainly inspired by this StackOverflow question and my need to perform string 2 array conversions in bash.