0

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 replaced with some function call.

How to do it by sed command?

Andy Lin
  • 397
  • 1
  • 2
  • 21
  • Not really. In my case, it should delete everything, including points A and B, not anything between points A and B. – Andy Lin Apr 12 '21 at 08:06
  • 1
    If you look closely at [this answer](https://stackoverflow.com/a/5179968/6770384) you see that they actually delete `A` and `B` but then re-insert them again because that was wanted in the other question. In your case, just don't re-insert `A` and `B` and you are good to go. – Socowi Apr 12 '21 at 08:52

2 Answers2

2

Would you try the following:

sed '
:a                                              ;# define a label "a"
/printf("<style type=\\"text\/css\\">\\n");/ {  ;# if the line matches the string, enter the {block}
N                                               ;# read the next line
/printf("<\/style>\\n");/! ba                   ;# if the line does not include the ending pattern, go back to the label "a"
s/.*/replacement function call/                 ;# replace the text
}
' A.txt
tshiono
  • 21,248
  • 2
  • 14
  • 22
1

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
Socowi
  • 25,550
  • 3
  • 32
  • 54