linuxbashsed

sed - replace paragraph that begins with A and ends with B with strings


I have a bunch of text files in which many paragraphs begin with printf("<style type=\"text/css\">\n"); and end with printf("</style>\n");

For example,

A.txt

...
...
printf("<style type=\"text/css\">\n");
...
...
...
    printf("</style>\n"); // It may started with several Spaces!
...
...

I want this part to be replaced with some function calls.

How to do it with the sed command?


Solution

  • To replace a block of lines starting with A and ending with B by the text R, use sed '/A/,/B/cR'. Just make sure that you correctly escape the special symbols /, \ and ; in your strings. For readability I used variables:

    start='printf("<style type=\\"text\/css\\">\\n")\;'
    end='printf("<\/style>\\n")\;'
    replacement='somefunction()\;'
    sed "/^ *$start/,/^ *$end/c$replacement" yourFile