9

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.

4 Answers 4

19

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/')
Sign up to request clarification or add additional context in comments.

3 Comments

Hey I don't have the -E option working on my machine, and I don't see it on the man page
It's an alias for -r which is extended regex, I guess you are using linux then... -E is more portable (supported on Mac ect where -r isn't). My preference is -r but always use -E when answering question if the platform is unknown... It's always confused my why the man pages don't say it's supported.
Ok well that's cool I like your solution and it works with -r for me. Thanks!
7

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

Comments

2
$ STR='firstWord###secondWord'
$ eval $(echo $STR | sed 's:^:V1=":; /###/ s::";V2=": ;s:$:":')
$ echo $V1
firstWord
$ echo $V2
secondWord

Comments

2

This is how I would do it with zsh:

myVAR="firstWord###secondWord"
<<<$myvar sed 's/###/ /' | read myFIRST mySECOND

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.