Linux shell script: split the string, put them in an array, and then pass through them

Possible duplicate:
Split string based on separator in Bash?

In a bash script, how do I split a line with a type delimiter ; and iterate over the resulting array?

+16
bash
Sep 10 '09 at 18:36
source share
5 answers

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

One trick I like to use is to set the inter-field separator (IFS) to the separator character. This is especially useful for iterating through a space or returning delimited results for any of several unix commands.

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

 export IFS=";" sentence="one;two;three" for word in $sentence; do echo "$word" done 

Note: in the regular setup of Bourne-shell scripts and during export, IFS will occur on two separate lines (IFS = 'x'; export IFS;).

+39
Sep 10 '09 at 19:02
source share

Here's an ashirazi answer option that doesn't rely on $IFS . He has his own problems, which I will discuss below.

 sentence="one;two;three" sentence=${sentence//;/$'\n'} # change the semicolons to white space for word in $sentence do echo "$word" done 

I used a new line here, but you can use the " \t " tab or the space bar. However, if any of these characters is in the text, it will also be split. What is the advantage of $IFS - it can not only enable the delimiter, but also disable the standard ones. Just make sure you save its value before changing it, as others suggested.

+8
Sep 10 '09 at 19:25
source share

If you don't want to mess with IFS (maybe for code inside a loop), this might help.

If you know that your string will not have spaces, you can replace the " ; " with a space and use the for / in construct:

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

But if you can have a space, then for this approach you will need to use a temporary variable to hold the "rest" as follows:

 #local str rest rest=$STR 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\"" done 
+7
Sep 10 '09 at 19:44
source share

Here is an example of code that you can use:

 $ STR="String;1;2;3" $ for EACH in `echo "$STR" | grep -o -e "[^;]*"`; do echo "Found: \"$EACH\""; done 

grep -o -e "[^;] *" will select something that is not ';', therefore dividing the string by ';'.

Hope this helps.

+1
Sep 10 '09 at 18:50
source share
 sentence="one;two;three" a="${sentence};" while [ -n "${a}" ] do echo ${a%%;*} a=${a#*;} done 
+1
Nov 26 '11 at 19:01
source share



All Articles