Sed——多行模式学习笔记

多行模式空间

sed能查看模式空间的多个行,这就是允许匹配模式扩展到多行上。

多行追加下一行(N)

多行Next(N)命令通过读取新输入行,并将它添加到模式空间的现有内容之后来创建多行模式空间。模式空间最初的内容和新的输入行之间用换行符分隔。在模空间中嵌入的换行符可以利用转义序列"\n"来匹配。在多行模式空间中,元字符"^“匹配空间中的第一个字符,而不匹配换行符后面的字符。”$"只匹配模式空间中最后的换行符,而不匹配任何嵌入的换行符。执行N命令后,控制将被传递给脚本中的后续命令。

Consult Section 3.1 in the Owner and Operator
Guide for a description of the tape drives
available on your system.

/Operator$/{
N
s/Owner and Operator\nGuide /Installation Guide\	# 末位替换换行符"\"
/
}

result:
Consult Section 3.1 in the Installation Guide
for a description of the tape drives
available on your system.

Consult Section 3.1 in the Owner and Operator
Guide for a description of the tape drives
available on your system.
Look in the Owner and Operator Guide shipped with your system.
Two manuals are provided including the Owner and
Operator Guide and the User Guide.
The Owner and Operator Guide is shipped with your system.

s/Owner and Operator Guide/Installation Guide/
/Owner/{
N
s/ *\n/ /	# 将普通	
s/Owner and Operator Guide */Installation Guide\
/
}

result:
Consult Section 3.1 in the Installation Guide
for a description of the tape drives
available on your system.
Look in the Installation Guide shipped with your system.
Two manuals are provided including the Installation Guide
and the User Guide.
The Installation Guide is shipped with your system.
多行删除(D)

删除模式空间中直到第一个嵌入的换行符的这部分内容。它不会导致读入新的输入行,相反,它返回到脚本的顶端,将这些指令应用于模式空间剩余的内容。

 This line is followed by 1 line.

 This line is followed by 2 line.


 This line is followed by 3 line.



 This line is followed by 4 line.




 This is the end.

# 删除多余空格,仅保留一行空格。
/^$/{
N
/^\
$/D
}

result:

 This line is followed by 1 line.

 This line is followed by 2 line.

 This line is followed by 3 line.

 This line is followed by 4 line.

 This is the end.


多行打印§

该命令输出多行模式空间的第一部分,直到第一个嵌入的换行符为止。在执行完脚本的最后一个命令之后,模式空间的内容自动输出(-n选项或#n抑制这个默认动作)。因此,当默认的输出被抑制或脚本中的控制流更改,以至不能到达脚本的底部时,需要使用打印命令(P或p).Print命令经常出现在Next命令之后和Delete命令之前。这三个命令能建立一个输入/输出循环,用来维护两行的模式空间,但一次只输出一行。这个循环的目的是只输出模式空间的第一行,然后返回到脚本的顶端将所有的命令应用于模式空间的第二行。没有这个 循环,当执行脚本中的最后一个命令时,模式空间中的这两行将被输出。

Here are examples of the UNIX
System. Where UNIX
System appears, it should be the UNIX
Operating System.

/UNIX$/{
N	# 将一行新的输入行加入模式空间
/\
System/{
s// Operating &/
P	# 替换命令应用于多行模式空间之后,模式空间的第一部分被Print命令输出,然后被Delete命令删除。
D	# 阻止脚本到达底部,输出两行并清除模式空间的内容。Delete命令保护了模式空间的第二部分,并将控制转移脚本顶端。顶端所有的编辑命令都可以被应用于一行。
}
}

result:
Here are examples of the UNIX Operating
System. Where UNIX Operating
System appears, it should be the UNIX
Operating System.

N、P、D的联合使用,是为了一旦进行跨越两行的替换,就打印第一行并且把它从模式空间删除。第二部分保留在模式空间中,将控制转移到脚本的顶端,这时检查是否在该行上还有其他的匹配字符。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值