Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 752
JDS Avatar asked Nov 15 '12 23:11

JDS


1 Answers

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/')
like image 91
Chris Seymour Avatar answered Oct 20 '22 04:10

Chris Seymour