繁体   English   中英

使用 sed - 如何在第一次出现变量后替换第一次出现的字符串

[英]Using sed - how to replace the first occurrence of a string on the line after the first occurrence of a variable

我有位分层问题,用sed将使用一个变量作为一个搜索字符串,为此多行。 我可以做或做,但不能同时做。 我正在处理一个看起来像这样的 xml 文件。

<tag property="search1">
        string
</tag>
<tag property="search2">
        string
</tag>
<tag property="search3">
        string
</tag>

我正在尝试使用脚本根据其前一行上的“搜索”字符串的数量,将“字符串”依次替换为另一个值。 脚本会增加一个计数器来执行此操作。

如果“$n”已知,我可以在“search$n”之后找到并替换“string”:

$ sed '$!N;/search2/ s/\string/foo/;P;D' test
<tag property="search1">
        string
</tag>
<tag property="search2">
        foo
</tag>
<tag property="search3">
        string
</tag>

我可以根据变量搜索替换字符串:

$ n=2 
$ sed "/search$n/ s/search/foo/" test
<tag property="search1">
        string
</tag>
<tag property="foo2">
        string
</tag>
<tag property="search3">
        string
</tag>

但我一直无法弄清楚如何将两者结合起来:

$ sed '$!N;/search$n/ s/\string/foo/;P;D' test

上述命令有效; 因为它不会抛出错误,但它不会解析变量- 我试过转义它,并将它放在双引号或单引号中并转义它们。 允许我在 sed 中解析多行的参数似乎需要单引号,而在搜索字段中读取变量需要双引号......

我在 OSX 上使用 gnu-sed。 以下是我尝试过的其他一些事情:

sed "/search$n/,+1s/string/foo/" test
sed '/search$n/,+1s/string/foo/' test
sed "/search$n/,+1s s/string/foo/" test
sed '/search$n/,+1 s/string/foo/' test
sed '' -e '/search$n/ {' -e 'n; s/string/foo/' -e '}' test 
sed '' -e '/search$n/ {' -e 'n; s/.*/foo/' -e '}' test 
sed '/search$n/!b;n;c/foo/' test 
sed '' -e '/search$n/!b;n;string' test 
sed '' -e "/search$n/ {' -e 'n; s/string/foo/' -e '}" test 
sed '' -e "/search$n/ {' -e 'n; s/.*/foo/g' -e '}" test 
sed '' -e "/search$n/ s/string/foo/" test 
sed -e "/search$n/ s/string/foo/" test 
sed "/search$n/ s/string/foo/" test 

您需要声明n=2 (不是i=2 ),然后使用双引号来允许变量扩展。

但是,您需要注意$! 这是 Bash 特有的。 您可以使用

n=2
sed '$!'"N;/search$n/ s/string/foo/;P;D" test

输出:

<tag property="search1">
        string
</tag>
<tag property="search2">
        foo
</tag>
<tag property="search3">
        string
</tag>

'$!'"N;/search$n/ s/string/foo/;P;D"$! (不支持变量扩展)和N;/search$n/ s/string/foo/;P;D (支持变量扩展)。

这可能对你有用(GNU sed):

n=2
sed '/search'"$n"'/{n;s/string/foo/}' file

n设置为2

匹配search2 ,打印当前行并获取下一行。

如果下面的行包含string替换stringfoo

以下行可能不包含string但包含search2 ,在这种情况下:

sed ':a;/search'"$n"'/{n;s/string/foo/;Ta}' file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM