【问题标题】:sed - replace paragraph that begins with A and ends with B with strings [duplicate]sed - 用字符串替换以A开头并以B结尾的段落[重复]
【发布时间】:2021-04-12 07:40:59
【问题描述】:

我有一堆文本文件,其中许多段落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命令怎么做?

【问题讨论】:

  • 并非如此。就我而言,它应该删除所有内容,包括点 A 和 B,而不是点 A 和 B 之间的任何内容。
  • 如果您仔细查看this answer,您会发现它们实际上删除了AB,但随后又重新插入它们,因为在另一个问题中需要这样做。在您的情况下,只需不要重新插入 AB 即可。

标签: linux bash sed


【解决方案1】:

你会尝试以下方法:

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

【讨论】:

    【解决方案2】:

    要将以A 开头并以B 结尾的行块替换为文本R,请使用sed '/A/,/B/cR'。只需确保正确转义字符串中的特殊符号 /\;。为了便于阅读,我使用了变量:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 2013-03-02
      相关资源
      最近更新 更多