开发者

Need help in manipulating string variable

开发者 https://www.devze.com 2023-02-28 21:05 出处:网络
I have written a shell script to do some开发者_如何学C processing and have to manipulate a variable. Basically, the variable is like this --

I have written a shell script to do some开发者_如何学C 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 ?


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


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


Try this

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

精彩评论

暂无评论...
验证码 换一张
取 消