I have a variable in my shell script of the form
myVAR = "firstWord###secondWord"
I would like to use grep or some other tool to separate into two variables such that the final result is:
myFIRST = "firstWord"
mySECOND = "secondWord"
How can I go about doing this? #{3} is what I want to split on.
Using substitution with sed
:
echo $myvar | sed -E 's/(.*)#{3}(.*)/\1/'
>>> firstword
echo $myvar | sed -E 's/(.*)#{3}(.*)/\2/'
>>> secondword
# saving to variables
myFirst=$(echo $myvar | sed -E 's/(.*)#{3}(.*)/\1/')
mySecond=$(echo $myvar | sed -E 's/(.*)#{3}(.*)/\2/')
The best tool for this is sed :
$ echo "firstWord###secondWord" | sed 's@###@\
@'
firstWord
secondWord
A complete example :
$ read myFIRST mySECOND < <(echo "$myvar" | sed 's@###@ @')
$ echo $myFIRST
firstWord
$ echo $mySECOND
secondWord
$ STR='firstWord###secondWord'
$ eval $(echo $STR | sed 's:^:V1=":; /###/ s::";V2=": ;s:$:":')
$ echo $V1
firstWord
$ echo $V2
secondWord
This is how I would do it with zsh:
myVAR="firstWord###secondWord"
<<<$myvar sed 's/###/ /' | read myFIRST mySECOND
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.