Abhinay
Abhinay

Reputation: 635

How to split a string and store into array based on pattern in shell script

I have a string like

string = ionworldionfriendsionPeople

How can I split it and store in to array based on the pattern ion as

array[0]=ionworld
array[1]=ionfriends
array[2]=ionPeople

I tried IFS but I am unable to split correctly. Can any one help on this.

Edit: I tried

test=ionworldionfriendsionPeople

IFS='ion' read -ra array <<< "$test"

Also my string may sometimes contains spaces like

string = ionwo rldionfri endsionPeo ple

Upvotes: 0

Views: 675

Answers (4)

Ali ISSA
Ali ISSA

Reputation: 408

# To split string :
# -----------------
string=ionworldionfriendsionPeople
echo "$string" | sed -e "s/\(.\)ion/\1\nion/g"

# To set in Array:
# ----------------
string=ionworldionfriendsionPeople
array=(`echo "$string" | sed -e "s/\(.\)ion/\1 ion/g"`)

# To check array content :
# ------------------------
echo ${array[*]}

Upvotes: 1

anubhava
anubhava

Reputation: 785681

Using grep -oP with lookahead regex:

s='ionworldionfriendsionPeople'
grep -oP 'ion.*?(?=ion|$)' <<< "$s"

Will give output:

ionworld
ionfriends
ionPeople

To populate an array:

arr=()
while read -r; do
   arr+=("$REPLY")
done < <(grep -oP 'ion.*?(?=ion|$)' <<< "$s")

Check array content:

declare -p arr
declare -a arr='([0]="ionworld" [1]="ionfriends" [2]="ionPeople")'

If your grep doesn't support -P (PCRE) then you can use this gnu-awk:

awk -v RS='ion' 'RT{p=RT} $1!=""{print p $1}' <<< "$s"

Output:

ionworld
ionfriends
ionPeople

Upvotes: 1

chepner
chepner

Reputation: 531948

You can use some POSIX parameter expansion operators to build up the array in reverse order.

foo=ionworldionfriendsionPeople
tmp="$foo"
while [[ -n $tmp ]]; do
    # tail is set to the result of dropping the shortest suffix
    # matching ion*
    tail=${tmp%ion*}
    # Drop everything from tmp matching the tail, then prepend
    # the result to the array
    array=("${tmp#$tail}" "${array[@]}")
    # Repeat with the tail, until its empty
    tmp="$tail"
done

The result is

$ printf '%s\n' "${array[@]}"
ionworld
ionfriends
ionPeople

Upvotes: 3

choroba
choroba

Reputation: 242038

If your input string never contains whitespace, you can use parameter expansion:

#! /bin/bash
string=ionworldionfriendsionPeople
array=(${string//ion/ })
for m in "${array[@]}" ; do
    echo ion"$m"
done

If the string contains whitespace, find another character and use it:

ifs=$IFS
IFS=@
array=(${string//ion/@})
IFS=$ifs

You'll need to skip the first element in the array which will be empty, though.

Upvotes: 1

Related Questions