我正在学习sed。直到我遇到N(接下来的多行),一切似乎都很好。我出于练习/理解/上下文的目的创建了此文件(guide.txt)。这是该文件的内容...
This guide is meant to walk you through a day as a Network
Administrator. By the end, hopefully you will be better
equipped to perform your duties as a Network Administrator
and maybe even enjoy being a Network Administrator that much more.
Network Administrator
Network Administrator
I'm a Network Administrator
因此,我的目标是用“系统用户”代替“网络管理员”的所有实例。因为“网络管理员”的第一个实例由换行符(\ n)分隔,所以我需要多行下一个运算符(N)来附加以“管理员”开头的行和前一行以“网络\ n”结尾的行。没问题。但我也想抓住所有其他“网络管理员”单行实例。
从我的研究中,我了解到我将需要两个替换命令。一个用于换行符分隔的字符串,另一个用于其他字符串。另外,由于最后一行包含替换匹配项,而下一行包含多行,因此发生了一些冲突。所以我做这个...
$ sed '
> s/Network Administrator/System User/
> N
> s/Network\nAdministrator/System\nUser/
> ' guide.txt
这将返回这些结果...
This guide is meant to walk you through a day as a System
User. By the end, hopefully you will be better
equipped to perform your duties as a System User
and maybe even enjoy being a Network Administrator that much more.
System User
Network Administrator
I'm a System User
我认为单行替换将捕获“网络管理员”的所有“常规”实例并将其替换为“系统用户”,而多行语句将在换行符分离的实例上发挥其魔力,但是随着您可以看到它返回了,我认为是出乎意料的结果。
经过一番摆弄之后,我落在了这个...
$ sed '
> s/Network Administrator/System User/
> N
> s/Network\nAdministrator/System\nUser/
> s/Network Administrator/System User/
> ' guide.txt
而且,我得到了期望的输出...
This guide is meant to walk you through a day as a System
User. By the end, hopefully you will be better
equipped to perform your duties as a System User
and maybe even enjoy being a System User that much more.
System User
System User
I'm a System User
为什么这样做有效,而原始的sed脚本却无效?我真的很想了解这一点。
在此先感谢您的帮助。