Adding a new line after a pattern match

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Elizabeth H
    New Member
    • Jan 2011
    • 19

    Adding a new line after a pattern match

    Hi,

    I have a question regarding adding lines basically using sed after a pattern match. My code would look like

    Several lines in the file
    # abcd ##{{{
    variable 1
    variable 2
    variable 3
    .
    .
    .
    ## }}}

    And I need to add a for loop just before the 'abcd' fold closes and my new code shud look like
    Several lines in the file
    # abcd ##{{{
    variable 1
    variable 2
    variable 3
    .
    .
    .
    for i in something
    do
    XXXX
    done
    ## }}}

    I am not able to correctly match the pattern and get the abcd fold exactly as there are several other folds in the file.Please advise, what way to go
  • Elizabeth H
    New Member
    • Jan 2011
    • 19

    #2
    Hi again

    I think I was able to figure out how to do it. But I came across a problem.This is what I tried
    sed -i -e '/^ # abcd/,/^ ## }}}$/s/ ## }}}/ $insert\n ## }}}/'
    If I use some string like "STRING" instead of the insert variable, it works perfectly fine. But when I try insert="for ....do...done" and try it with $insert it doesnt get substitued with the value of insert. I tried several different ways but doesnt seem to work.

    Comment

    • numberwhun
      Recognized Expert Moderator Specialist
      • May 2007
      • 3467

      #3
      Are you trying to do a system level for loop? (ie: bash or ksh) If so, then you need to use back tics around the for loop and not double quotes. Back tics will execute a system level command and return its value(s).

      As for the sed, you can do all of that pattern matching in Perl and use Perl's much more powerful regex engine. sed is just one precursor to Perl.

      Also, looking at your original question, it has me a little lost. Your explanation of what you are trying to do is a bit vague. Is there any way that you could clean it up and give a bit more detail of what you are trying to do and also provide actual code examples of what you are trying?

      Regards,

      Jeff

      Comment

      Working...