简体   繁体   中英

Shell scripting using grep to split a string

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 :

$ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM