Urvashi Urvashi - 4 years ago 96
Bash Question

Split string after matching the word in shell

I have a csv file in that values are like:

Wt-Do-U-Do-Wit-The-Black,black
Yay-Its-Your-Birthday-Black,black
You-Are-My-Sunshine-Happy-Birthday-Red,red
You-Are-Special-Navy-Blue,navy-blue
You-Dont-Look-A-Day-Over-Fabulous-Green,green
You-My-Friend-Are-Ridiculously-Fabulous-Happy-Birthday-Pink,pink


I want to split each string before colour name comes.For Ex:

str1=Wt-Do-U-Do-Wit-The
str1=Yay-Its-Your-Birthday
str1=You-Are-My-Sunshine-Happy-Birthday
str1=You-Are-Special
str1=You-Dont-Look-A-Day-Over-Fabulous
str1=You-My-Friend-Are-Fabulous-Happy-Birthday


For searching the string i am using :-

if [ "$string" == *"Black"* ] && [ "$string" == *"White"* ] ; then
echo "It's there!"
else
echo "SOrry"
fi


It is searching fine. But how can I split the string?

Another way I used :

colour_arr[0]='Red'
colour_arr[1]='Black'
colour_arr[2]='Navy-Blue'
colour_arr[3]='White'
inarray=$(echo ${colour_arr[@]} | grep -o "$string" | wc -w)
echo "$inarray"


But this is not working.

Answer Source

you can use sed; inspired from this answer

I simplified the problem a little since you parsed the strings already correctly; using this input file:

This is red colour
Ball is  black colour
some more words before red and more after

for the second part of the string; starting with the color name:

sed -n -e 's/^.*\(\(red\|black\).*\)/\1/p' test

gives:

red colour
black colour
red and more after

and

sed -n -e 's/\(^.*\)\(\(red\|black\).*\)/\1/p' test

gives:

This is 
Ball is  
some more words before

I won't explain all the options; since they are well explained in the answer I referred to. You can use sed on a bash variable using:

leftpart=$(sed -n -e 's/\(^.*\)\(\(red\|black\).*\)/\1/p' <<< $INPUT_STRING)

EDIT after the OP changed the input format: my answer still applies; just replace red with Red. The rest applies the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download