Shicheng Guo
Shicheng Guo

Reputation: 1293

string split in bash

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?

Upvotes: 1

Views: 292

Answers (2)

Gene
Gene

Reputation: 46960

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

Upvotes: 4

riteshtch
riteshtch

Reputation: 8769

$declare -a array=($(echo "ParisABFranceABEurope" | awk -F 'AB' '{for (i=1;i<=NF;i++) print $i}'))
$ echo "${array[@]}"
Paris France Europe

Upvotes: 0

Related Questions