LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1144|回复: 3

谁给我解释一下这个sed命令

[复制链接]
发表于 2010-9-17 00:11:36 | 显示全部楼层 |阅读模式
为什么这个命令之替换了第一次的pattern

s命令后的pattern部分为什么是空地雅?

  1. sed '0,/RE/s//to_that/' file   # change only the first match
复制代码
发表于 2010-9-17 13:53:00 | 显示全部楼层
最近超爱看IEEE 1003.1-2004啊~~~
http://www.opengroup.org/onlinepubs/009695399/utilities/sed.html

Q:为什么这个命令只替换了第一次的pattern?
A:如下所言。
[2addr]s/BRE/replacement/[color="Red"]flags
...
...
The value of flags shall be zero or more of:
...
[color="Red"]g        Globally substitute for all non-overlapping instances of the BRE rather than just the first one. If both g and n are specified, the results are unspecified.
...

Q:s命令后的pattern部分为什么是空的呀?
A:如下所言。
The sed utility shall support the BREs described in the Base Definitions volume of IEEE Std 1003.1-2001, Section 9.3, Basic Regular Expressions, with the following additions:

  • In a context address, the construction "\cBREc", where c is any character other than backslash or <newline>, shall be identical to "/BRE/". If the character designated by c appears following a backslash, then it shall be considered to be that literal character, which shall not terminate the BRE. For example, in the context address "\xabc\xdefx", the second x stands for itself, so that the BRE is "abcxdef".
  • The escape sequence '\n' shall match a <newline> embedded in the pattern space. A literal <newline> shall not be used in the BRE of a context address or in the substitute function.
  • [color="Red"]If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.
不那么明显的一点是:如果采用
/BRE1/, /BRE2/ s//replacement/
的话,地址区间内的第一行(即包含BRE1的那行)使用的pattern就是BRE1,而地址区间内剩下行使用的pattern都是BRE2。如果清楚sed的双地址其实是一个具有俩状态的状态机,这点就不难理解。
回复 支持 反对

使用道具 举报

发表于 2010-9-17 17:47:21 | 显示全部楼层
great~
回复 支持 反对

使用道具 举报

 楼主| 发表于 2010-9-17 18:34:14 | 显示全部楼层
哇,非常好,
非常感谢你如此详尽的回答。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表