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?

Shicheng Guo
  • 1,233
  • 16
  • 19
  • 2
    Possible duplicate of [How do I split a string on a delimiter in Bash?](http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash) – Cripto Feb 18 '16 at 02:25

2 Answers2

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
Gene
  • 46,253
  • 4
  • 58
  • 96
  • 2
    Nicely done; to encourage good habits, please double-quote `${words[0]}`, ..., and use `-r` with `read`. – mklement0 Feb 18 '16 at 03:05
0
$declare -a array=($(echo "ParisABFranceABEurope" | awk -F 'AB' '{for (i=1;i<=NF;i++) print $i}'))
$ echo "${array[@]}"
Paris France Europe
riteshtch
  • 8,629
  • 4
  • 25
  • 38
  • This works for the sample input, but the caveat is that it makes the resulting tokens subject to pathname expansion. – mklement0 Feb 18 '16 at 03:29