Shell scripting using grep to split a string
27,130
Solution 1
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/')
Solution 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
Solution 3
$ STR='firstWord###secondWord'
$ eval $(echo $STR | sed 's:^:V1=":; /###/ s::";V2=": ;s:$:":')
$ echo $V1
firstWord
$ echo $V2
secondWord
Solution 4
This is how I would do it with zsh:
myVAR="firstWord###secondWord"
<<<$myvar sed 's/###/ /' | read myFIRST mySECOND
Author by
JDS
Updated on July 26, 2022Comments
-
JDS almost 2 years
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.
-
JDS over 11 yearsHey I don't have the -E option working on my machine, and I don't see it on the man page
-
Chris Seymour over 11 yearsIt'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. -
JDS over 11 yearsOk well that's cool I like your solution and it works with -r for me. Thanks!