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 :

$ 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
Share:
27,130
JDS
Author by

JDS

Updated on July 26, 2022

Comments

  • JDS
    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
    JDS over 11 years
    Hey I don't have the -E option working on my machine, and I don't see it on the man page
  • Chris Seymour
    Chris Seymour over 11 years
    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.
  • JDS
    JDS over 11 years
    Ok well that's cool I like your solution and it works with -r for me. Thanks!