替换可能跨越两行的模式

替换可能跨越两行的模式

我试图了解N选项在 Sed 编辑器中的工作原理。我的目标是改变“系统管理员”“桌面用户”在里面“文件01”,同时制动线甚至在最后一行。 sed 不会赶上最后一行,因为不会有下一行。还需要进行另一项修改,例如添加:

sed 's/System Administrator/Desktop User/',但是这个和:

sed 'System\nAdministrator/Desktop\nUser/'以意想不到的方式切换(对我来说),使得其中一个命令停止为最后一行或最后两行工作。这种情况要么发生N在两人之间,要么发生在两人之前。我正在使用 GNU Sed 版本 4.4 。

#cat file01
The first meeting of the Linux System
Administrator's group will be held on Tuesday.
Another line
And here we have: System Administrator's Group as well.
1.System Administrator's group.
2.System Administrators Group.
3.System Administrators Group.
The first meeting of the Linux System
Administrator's group will be held on Tuesday.
System Administrators Group.

情况1,之后的两个命令N

# sed '
>N
>s/System\nAdministrator/Desktop\nUser/
>s/System Administrator/Desktop User/
> ' file01
The first meeting of the Linux Desktop
User's group will be held on Tuesday.
Another line
And here we have: Desktop User's Group as well.
1.Desktop User's group.
2.System Administrators Group.
3.Desktop Users Group.
The first meeting of the Linux System
Administrator's group will be held on Tuesday.
Desktop Users Group.

案例2sed 's/System Administrator/Desktop User/'N

# sed '
> s/System Adminitrator/Desktop User/
> N
> s/System\nAdministrator/Desktop\nUser/
> ' file01
The first meeting of the Linux Desktop
User's group will be held on Tuesday.
Another line
And here we have: System Administrator's Group as well.
1.Desktop User's group.
2.System Administrators Group.
3.Desktop Users Group.
The first meeting of the Linux System
Administrator's group will be held on Tuesday.
System Administrators Group.

这对我来说很奇怪,无法弄清楚出了什么问题。 [编辑]:进一步细节。

我正在寻找替代品“系统管理员”“桌面用户”。此外,如果一行以“系统”结尾,下一行以“管理员”开头,我会将它们相应地替换为“桌面”和“用户”。所有这些都取自一本书,但输出与书上的内容不符。我最终不知道出了什么问题。我发现描述我的问题的唯一世界是优先级,我道歉,看来我错了。

答案1

这实际上与优先级(通常与运算符相关)没有任何关系,而是与发出命令的顺序有关。


看一下问题中的第一个例子:

N
s/System\nAdministrator/Desktop\nUser/
s/System Administrator/Desktop User/

这将成对读取行并对其应用两个替换。如果该对中的第二行以SystemAdministrator在接下来的第三行上)结尾,那么它将无法检测到。这意味着当字符串跨越奇数行和偶数行时,不会被替换

看一下问题中的第二个示例(拼写已更正):

s/System Administrator/Desktop User/
N
s/System\nAdministrator/Desktop\nUser/

这将更改当前行上的字符串,读取下一行并使用中间的换行符更改字符串。 这不会更改带有完整字符串副本的奇数行(或者只有奇数行System)。


使用 GNU sed

:top
N
$s/System\(.\)Administrator/Desktop\1User/g
b top

该脚本循环并将文件的所有行读入模式空间。一旦到达输入的最后一行,它就会在全局范围内执行替换,同时允许两个单词之间存在任何字符(也可以使用\([ \n]\)) 而不是\(.\))。

结果将是

The first meeting of the Linux Desktop
User's group will be held on Tuesday.
Another line
And here we have: Desktop User's Group as well.
1.Desktop User's group.
2.Desktop Users Group.
3.Desktop Users Group.
The first meeting of the Linux Desktop
User's group will be held on Tuesday.
Desktop Users Group.

答案2

当搜索可能跨越两行的模式时,与andN一起使用- 又名 aPDN;P;D cycle,以便模式空间1中始终有两行:

sed '$!N
s/System\nAdministrator/Desktop\nUser/
s/System Administrator/Desktop User/g
P
D' <infile

注意这s/System\nAdministrator/Desktop\nUser/gnu sed语法。便携式你会做

s/System\nAdministrator/Desktop\
User/

1:它从第 1-2 行开始,在 P;D 之后处理第 2-3 行,然后是第 3-4 行,依此类推...

相关内容