user496934
user496934

Reputation: 4020

Need help in manipulating string variable

I have written a shell script to do some processing and have to manipulate a variable. Basically, the variable is like this --

vaa="set policy:set cli"

My purpose is to split it into two variables based on the position of ":". To get the right end, I am doing this --

vaa1=${vaa#*:}
echo ${vaa1}   //this prints "set cli" which I want

However, I am not able to get the left part of the string "set policy". I tried doing this --

vaa2=${vaa%*:}

But it didn't work and I am getting the whole string--"set policy:set cli". Any ideas on how to get the left part ?

Upvotes: 2

Views: 103

Answers (3)

Tom Hazel
Tom Hazel

Reputation: 3502

Try this

vaa2=${vaa%:*}
echo ${vaa2}

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342363

This is how to do it (bash)

$ vaa="set policy:set cli"
$ IFS=":"
$ set -- $vaa
$ echo $1
set policy
$ echo $2
set cli

or read into an array

$ IFS=":"
$ read -a array <<< "$vaa"
$ echo "${array[0]}"
set policy
$ echo "${array[1]}"
set cli

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246807

You need to alter your pattern

echo ${vaa#*:}  
# from the beginning of the string, 
# delete anything up to and including the first :

echo ${vaa%:*}  
# from the end of the string, 
# delete the last : and anything after it

Upvotes: 1

Related Questions