sed-将以A开头、以B结尾的段落替换为字符串



我有一堆文本文件,其中许多段落printf("<style type="text/css">n");开头,以printf("</style>n");结尾

例如,

A.txt

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

我想用一些函数调用来替换这个部分。

如何使用sed命令?

你会尝试以下操作吗:

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

要用文本R替换以A开始、以B结束的行块,请使用sed '/A/,/B/cR'。只需确保正确转义字符串中的特殊符号/;即可。为了可读性,我使用了变量:

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

最新更新