1

In a Bash script I would like to split a line into pieces and put them into an array.

The line:

ParisABFranceABEurope

I would like to split them in an array like this (with AB):

array[0] = Paris
array[1] = France
array[2] = Europe

I would like to use simple code, the command's speed doesn't matter. How can I do it?

1

2 Answers 2

4

Here is one that doesn't need sub-shells (i.e. it's all built-in). You'll need to pick a single delimiter character (here @) that can't appear in the data:

str='ParisABFranceABEurope'
IFS='@' read -r -a words <<< "${str//AB/@}"

echo "${words[0]}"
echo "${words[1]}"
echo "${words[2]}"

Drum roll, please...

$ source foo.sh
Paris
France
Europe
Sign up to request clarification or add additional context in comments.

1 Comment

Nicely done; to encourage good habits, please double-quote ${words[0]}, ..., and use -r with read.
0
$declare -a array=($(echo "ParisABFranceABEurope" | awk -F 'AB' '{for (i=1;i<=NF;i++) print $i}'))
$ echo "${array[@]}"
Paris France Europe

1 Comment

This works for the sample input, but the caveat is that it makes the resulting tokens subject to pathname expansion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.