用sed解析和替换多行 [英] parsing and replacing multiple lines with sed

查看:65
本文介绍了用sed解析和替换多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 sed 替换 3 行块,但遇到了一个奇怪的问题……我使用的脚本是

I am trying to replace blocks of 3 lines with sed and I'm running into a weird problem … the script I'm using is

/^#begin$/N;N;s/#begin\n\(.*\)\n#end/replaced \1/

在看起来像的输入文件上

On an input file that looks like

#begin
1
#end

它工作正常,我明白了

replaced 1

然而,如果在块之前有一行解析失败……同样的脚本应用于

However, if there is a line before the block the parse fails … the same script applied to

a line
#begin
1
#end

不会改变任何东西.如果我添加两行(说一行"后跟另一行"),它会再次起作用……我不明白为什么.有什么想法吗?

does not change anything. If I add two lines (say "a line" followed by "another line"), it works again … I can't understand why. Any thoughts ?

谢谢!

推荐答案

使用 { .. } 围绕特定模式的操作:

Use { .. } around the action on specific pattern:

/^#begin$/{N;N;s/#begin\n\(.*\)\n#end/replaced \1/}

例如:

$ cat file
a line
#begin
1
#end

$ sed '/^#begin$/{N;N;s/#begin\n\(.*\)\n#end/replaced \1/}' file
a line
replaced 1

某些版本的 sed (BSD) 要求在大括号前有一个尾随 ;.所以使用以下内容:

Some versions of sed (BSD) require a trailing ; before the end brace. So use the following:

sed '/^#begin$/{N;N;s/#begin\n\(.*\)\n#end/replaced \1/;}' file

这篇关于用sed解析和替换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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