1. Using tr command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
STR="123,456,567 5,343" | |
STR_ARRAY=(`echo $STR | tr "," "\n"`) | |
for x in "${STR_ARRAY[@]}" | |
do | |
echo "> [$x]" | |
done |
> [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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
> [123]
> [456]
> [567 5]
> [343]
This method works fine even if there are spaces.3. Using read command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
STR="123,456,567 5,343" | |
IFS="," read -ra STR_ARRAY <<< "$STR" | |
for x in "${STR_ARRAY[@]}" | |
do | |
echo "> [$x]" | |
done |
> [123]
> [456]
> [567 5]
> [343]
This method also works fine even though there are spaces in the $STR variable.4. Using sed command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
> [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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
STR="123,456,567 5,343" | |
set -- "$STR" | |
IFS=","; declare -a STR_ARRAY=($*) | |
for x in "${STR_ARRAY[@]}" | |
do | |
echo "> [$x]" | |
done |
> [123]
> [456]
> [567 5]
> [343]
This method also works fine.