[英]sed to match multiline range and replace
I have the file below我有下面的文件
next:
{
host = "http://nxt-newepisode.xcfm.crata.dive.com/err1.2.2/table/kenny.xml.gz"
};
second:
{
host = "http://nxt-secondepisode.xcfm.crata.dive.com/err1.2.2/table/kenny.xml.gz"
};
I want to replace the url based on nxt:{ host = ""
and second: { host = ""
.我想更换基于nxt:{ host = ""
和second: { host = ""
的 url 。 How can I filter this using sed with a multiline match, as these are on multiple lines?我如何使用 sed 和多行匹配过滤这个,因为它们在多行上?
I tried:我试过了:
sed -i '/second : {\rhost/s#"http://.*"#"next.com"#' file.txt
It doesn't work.它不起作用。 I am using \r
for new line but I also tried \n
.我正在使用\r
换行,但我也尝试过\n
。
If we can assume you have the URL on the second line below second:
you may use如果我们可以假设您在第二下方的第二行有 URL second:
您可以使用
sed -i '/second:/{N;N;s#"http://.*"#"next.com"#}' file
See this online sed
demo .请参阅此在线sed
演示。
N
appends the newline and then subsequent line to the pattern space. N
将换行符和后续行附加到模式空间。 So, the s
ubstitute command is run on the following text:因此, s
ubstitute 命令在以下文本上运行:
second:
{
host = "http://nxt-secondepisode.xcfm.crata.dive.com/err1.2.2/table/kenny.xml.gz"
If it is not known which line it is exactly, you may loop before you find the lione that starts with 0+ spaces, then host =
, and only then run substitution:如果不知道它到底是哪一行,您可以在找到以 0+ 个空格开头的 lione 之前循环,然后是host =
,然后才运行替换:
sed -i '/second:/{:a;n;/^ *host *=/!ba;s#"http://.*"#"next.com"#}' file
See this online sed
demo .请参阅此在线sed
演示。
Here,这里,
/second:/
- once a line contains second:
/second:/
- 一旦一行包含second:
:a
- set a label named a
:a
- 设置一个名为a
的 labeln
- discard the current pattern space and read the next line into it n
- 丢弃当前模式空间并将下一行读入其中/^ *host *=/!ba
- if the line does not ( !
) start with 0+ spaces, host
, 0+ spaces, =
, then go back ( b
) to label a
position /^ *host *=/!ba
- 如果行不 ( !
) 以 0+ 空格、 host
、 0+ 空格、 =
开头,则 go 返回 ( b
) 到 label a
Z4757FE07FD492A8DBEEDEA63s#"http://.*"#"next.com"#
- run the substitution. s#"http://.*"#"next.com"#
- 运行替换。 Literal spaces can be replaced with [[:space:]]*
, [[:blank:]]*
or \s*
to match any whitespace depending on what works in your sed
.文字空格可以替换为[[:space:]]*
、 [[:blank:]]*
或\s*
以匹配任何空格,具体取决于您的sed
中的内容。
This might work for you (GNU sed):这可能对您有用(GNU sed):
sed -E ':a;/^second:/{:b;n;/^\S+:/ba;/(^\s*host = ")[^"]*/s##\1newUrl#;Tb}' file
The replacement of a new url is confined to the second:
section.更换新的 url 仅限于second:
部分。
On encountering another section the processing is repeated.在遇到另一个部分时,重复处理。
Within a second:
section the line begining host = "
is sought and the value within double quotes replaced.在一second:
部分以host = "
开头的行被搜索并替换双引号内的值。
Otherwise the process is repeated until either condition above is met or the end of file.否则,重复该过程,直到满足上述任一条件或文件结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.