Saturday, April 9, 2022

[SOLVED] Shell scripting using grep to split a string

Issue

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.


Solution

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/')


Answered By - Chris Seymour
Answer Checked By - Robin (WPSolving Admin)