Saturday, 11 August 2018

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










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


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=";"
sentence="one;two;three"
for word in $sentence; do
echo "$word"
done



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


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...