How to add text after last pattern match using ed

前端 未结 2 1525
执念已碎
执念已碎 2021-01-16 20:31

This is how I am adding text before first pattern, I want to add after last pattern

FILE_NAME=\"folder/myfile.c++\"
STR_TO_ADD=\"string tha         


        
相关标签:
2条回答
  • 2021-01-16 21:08

    The solution by user0 is close, but if the last match falls on the last line of the file, it will find the previous one. Instead, go to the first line and search backward:

    1
    ?^$PATTERN
    a
    $STR_TO_ADD
    .
    

    I just posted this on my @ed1conf account a couple days ago so it's fresh in my mind.

    Additionally, if you're trying to add before the text (the example you already have), it will fail if the first match is on the first line because the "-1" goes before the start of the file. Instead, use the "i" command to insert the text rather than append it:

    $
    /^$PATTERN
    i
    $STR_TO_ADD
    .
    

    You might also need to ensure that "$STR_TO_ADD" doesn't contain any lines containing a single period or the variable-expansion will prematurely terminate the insertion (or appending).

    0 讨论(0)
  • 2021-01-16 21:28

    Go to last line of file and search pattern in backward direction.

    FILE_NAME="folder/myfile.c++"
    STR_TO_ADD="string that i want to add"
    PATTERN="banana"
    ed $FILE_NAME 2>NULL 1>NULL<<EOF
    $
    ?^$PATTERN
    a
    $STR_TO_ADD
    .
    wq
    EOF
    

    $ last line of file.
    ?^$PATTERN search pattern in backward direction from current line.

    0 讨论(0)
提交回复
热议问题