我在使用sed作为搜索字符串使用变量并跨多行执行此操作时遇到了一些分层问题。我可以做这两件事,但不能同时做。我正在处理一个类似于这样的xml文件。
<tag property="search1">
string
</tag>
<tag property="search2">
string
</tag>
<tag property="search3">
string
</tag>我试图顺序地将" string“替换为另一个值,具体取决于它前面行上的"search”字符串的数量,并使用一个脚本。这个脚本会增加一个计数器来完成这个任务。
如果已经知道"$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 发布于 2021-10-18 08:34:34
您需要声明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 (具有变量扩展支持)的连接。
发布于 2021-10-18 09:52:35
这可能对您有用(GNU sed):
n=2
sed '/search'"$n"'/{n;s/string/foo/}' file将n设置为2。
在search2上匹配,打印当前行并获取下一行。
如果下一行包含string,则将string替换为foo。
以下行可能不包含string,而是包含search2,在这种情况下:
sed ':a;/search'"$n"'/{n;s/string/foo/;Ta}' filehttps://stackoverflow.com/questions/69612597
复制相似问题