How do I do that?
$ for l in "aString that may haveSpaces IN IT" bar foo "bamboo" "bam boo"; do echo $l; done aString that may haveSpaces IN IT bar foo bamboo bam boo
What do I do if my string is in a bash
variable?
The simple approach of using the bash
string tokenizer will not work, as it splits on every space not just the ones outside quotes:
DavidPostill@Hal /f/test $ cat ./test.sh #! /bin/bash string='"aString that may haveSpaces IN IT" bar foo "bamboo" "bam boo"' for word in $string; do echo "$word"; done DavidPostill@Hal /f/test $ ./test.sh "aString that may haveSpaces IN IT" bar foo "bamboo" "bam boo"
To get around this the following shell script (splitstring.sh) shows one approach:
#! /bin/bash string=$(cat <<'EOF' "aString that may haveSpaces IN IT" bar foo "bamboo" "bam boo" EOF ) echo Source String: "$string" results=() result='' inside='' for (( i=0 ; i<${#string} ; i++ )) ; do char=$ if [[ $inside ]] ; then if [[ $char == \\ ]] ; then if [[ $inside=='"' && $ == '"' ]] ; then let i++ char=$inside fi elif [[ $char == $inside ]] ; then inside='' fi else if [[ $char == ["'"'"'] ]] ; then inside=$char elif [[ $char == ' ' ]] ; then char='' results+=("$result") result='' fi fi result+=$char done if [[ $inside ]] ; then echo Error parsing "$result" exit 1 fi echo "Output strings:" for r in "$" ; do echo "$r" | sed "s/\"//g" done
Output:
$ ./splitstring.sh Source String: "aString that may haveSpaces IN IT" bar foo "bamboo" "bam boo" Output strings: aString that may haveSpaces IN IT bar foo bamboo bam boo
Source: StackOverflow answer Split a string only by spaces that are outside quotes by choroba. Script has been tweaked to match the requirements of the question.