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

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

Output:> [123]
> [456]
> [567 5]
> [343]
This method works fine even if there are spaces.

3. Using read command

Output:> [123]
> [456]
> [567 5]
> [343]
This method also works fine even though there are spaces in the $STR variable.

4. Using sed command

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

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.