0

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
1
  • How did you use IFS? What code have you written? In order to help, we need a little more information. Commented Feb 12, 2016 at 16:57

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

1
# 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[*]}

Comments

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.