Search code examples
bashunixawksedcut

how to cut the pattern from a multiple line string and store to the new variable?


I have a string variable

$var="-- this is a  --
      -- comment --
      hellow
      world"

i need to cut the string string into two parts such that there are two new string variable

$var1="-- this is a  --
      -- comment --"

$var2="hellow
       world" 

i need the new line as it is in the $var1 $var2

what i have tried

var2=$(echo $var | sed 's/^--.*--//g')

i am not able to store the pattern in $var1 that it is deleting .

Note : hyphen is important and new line is important to maintain . have tried bash string manipulation but it doesn't worked


Solution

  • Simply use grep

    For var1

     grep  '\-\-.*\-\-'
    

    For var2

     grep -v '\-\-.*\-\-'
    

    As suggest by @123, we don't need escaping, if we use -- in grep command.

    So you can use this as well

    For var1

     grep  -- '--.*--'
    

    For var2

     grep -v '--.*--'