sed:在两行中找到模式,而不是在该模式之后替换 [英] sed: Find pattern over two lines, not replace after that pattern

查看:86
本文介绍了sed:在两行中找到模式,而不是在该模式之后替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哇,这真的吸引了我.我想这里需要一些技巧.这是我要替换的命令文本的输出值:

Wow, this one has really got me. Gonna need some tricky sed skill here I think. Here is the output value of command text I'm trying to replace:

...
fast
     n : abstaining from food

我要替换为的值是:

...
Noun
 : abstaining from food

我想这真是骗人.因为多次列出了快速",并且在行首的其他地方也列出了它.所以我想出了这个来定义范围:

This turns out to be tricker that I thought. Because 'fast' is listed a number of times and because it is listed in other places at the beginning of the line. So I came up with this to define the range:

sed '/fast/,/^     n : / s/fast/Noun/'

我以为可以,但是...不幸的是,这并没有结束替换,并且此匹配之后的其余输出将替换为Noun.赛后如何让Sed停止更换?更好的是,我可以找到两行模式匹配并替换吗?

Which I thought would do, but... Unfortunately, this doesn't end the replacement and the rest of the output following this match are replaced with Noun. How to get sed to stop replacement after the match? Even better, can I find a two line pattern match and replace it?

推荐答案

尝试一下:

sed "h; :b; \$b ; N; /^${1}\n     n/ {h;x;s//Noun\n/; bb}; \$b ; P; D"

不幸的是,Paul的答案读取了整个文件,这使您可能想要执行的其他处理变得困难.此版本成对读取行.

Unfortunately, Paul's answer reads the whole file in which makes any additional processing you might want to do difficult. This version reads the lines in pairs.

通过将sed脚本用双引号而不是单引号引起来,可以包含诸如位置参数之类的外壳变量.我建议用大括号括住它们,以便将它们与相邻字符分开放置.使用双引号时,必须注意要进行各种扩展的外壳.在此示例中,我转义了表示分支命令输入文件最后一行的美元符号.否则,外壳程序将尝试替换可能为空的变量$b的值,从而使sed不满意.

By enclosing the sed script in double quotes instead of single quotes, you can include shell variables such as positional parameters. I would recommend surrounding them with curly braces so they are set apart from the adjacent characters. When using double quotes, you'll have to be careful of the shell wanting to do its various expansions. In this example, I've escaped the dollar signs that signify the last line of the input file for the branch commands. Otherwise the shell will try to substitute the value of a variable $b which is likely to be null thus making sed unhappy.

另一种技术是使用单引号,并在每次拥有shell变量时将其关闭并打开:

Another technique would be to use single quotes and close and open them each time you have a shell variable:

sed 'h; :b; $b ; N; /^'${1}'\n     n/ {h;x;s//Noun\n/; bb}; $b ; P; D'
#   ↑open        close↑    ↑open                                close↑

我假设您预期结果中的"[/code]"是一个错字.让我知道是否可以.

I'm assuming that the "[/code]" in your expected result is a typo. Let me know if it's not.

这篇关于sed:在两行中找到模式,而不是在该模式之后替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆