linux shell script: split string, put them in an array then loop through them


Possible Duplicate:
Split string based on delimiter in Bash?

In a bash script how do I split string with a separator like ; and loop through the resulting array?

5/23/2017 12:16:53 PM

Accepted Answer

You can probably skip the step of explicitly creating an array...

One trick that I like to use is to set the inter-field separator (IFS) to the delimiter character. This is especially handy for iterating through the space or return delimited results from the stdout of any of a number of unix commands.

Below is an example using semicolons (as you had mentioned in your question):

export IFS=";"
for word in $sentence; do
  echo "$word"

Note: in regular Bourne-shell scripting setting and exporting the IFS would occur on two separate lines (IFS='x'; export IFS;).

9/10/2009 7:02:12 PM

If you don't wish to mess with IFS (perhaps for the code within the loop) this might help.

If know that your string will not have whitespace, you can substitute the ';' with a space and use the for/in construct:

#local str
for str in ${STR//;/ } ; do 
   echo "+ \"$str\""

But if you might have whitespace, then for this approach you will need to use a temp variable to hold the "rest" like this:

#local str rest
while [ -n "$rest" ] ; do
   str=${rest%%;*}  # Everything up to the first ';'
   # Trim up to the first ';' -- and handle final case, too.
   [ "$rest" = "${rest/;/}" ] && rest= || rest=${rest#*;}
   echo "+ \"$str\""

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow