关于sed 高级编程的一些疑问

qxh0724 2010-03-05 02:47:44
文件:data 的内容是:

The first meeting is the Linux System
Administrator's group will be held on Tudesday.
All System Administrators should attend this meeting.

我执行命令:sed 'N;p' data 的结果是:

The first meeting is the Linux System
Administrator's group will be held on Tudesday.
The first meeting is the Linux System
Administrator's group will be held on Tudesday.
All System Administrators should attend this meeting.

这个结果我是这么理解的,首先N,总是在执行sed编辑器命令之前将下一行文本读入到模式空间中,在达到最后一行时,因为没有下一行可以读入,所以N命令导致sed编辑器停止,最后一行数据没有被读入到模式空间中,所以结果是:
The first meeting is the Linux System
Administrator's group will be held on Tudesday.

然后p命令打印原始的数据内容:
The first meeting is the Linux System
Administrator's group will be held on Tudesday.
All System Administrators should attend this meeting.



执行:sed 'p;N' data 的结果是:

The first meeting is the Linux System
The first meeting is the Linux System
Administrator's group will be held on Tudesday.
All System Administrators should attend this meeting.
All System Administrators should attend this meeting.



以上结果是怎么得来的 不是很清楚,能否有经验的人士给我详细讲一下这个执行及得到结果的过程。




...全文
109 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qxh0724 2010-03-05
  • 打赏
  • 举报
回复
引用 1 楼 nevil 的回复:
sed -n 'n;p' file是打印偶数行,sed -n 'p;n' file是打印奇数行.\

现在你没有加-n参数,所以sed会先把这一行打出来,再分析是这一行奇数行还是偶数行决定是否再打一次

所以sed  'p;N'  data做如下分析
The first meeting is the Linux System <===输出第一行
The first meeting is the Linux System <===第一行是奇数行,打印
Administrator's group will be held on Tudesday.  <====输出第二行
All System Administrators should attend this meeting. <====输出第三行
All System Administrators should attend this meeting. <===第三行是奇数行,打印



是大写N 别搞错了 兄弟,我看书上N和n是有区别的
ghostwcy 2010-03-05
  • 打赏
  • 举报
回复
sed 'N;p',命令执行的步骤是:
读入第一行,用于执行指定的命令,指定的命令是N,将第二行读入到当前模式空间,下一个命令是p,将当前模式空间输出,没有命令了,sed会自动将当前模式空间内容输出。
此时sed自动读取下一行,由于第二行已经被读取了,所以,sed自动读取的是第三行,以下的循环同第一行、第二行。
直到文件结束。

如果文件有偶数行的话,N不会失败,输出的格式是121234345656....(数字代表行数)
如果有奇数行,最后一行是sed自动读取的,然后sed执行N命令失败,sed退出,退出前将当前模式空间内容输出,输出格式为:121234345656...(2N+1)(数字代表行数,最后一行只输出一次)

sed是行处理编辑,对每一行顺序执行指定的命令。按照这个思路去理解sed,会很容易的。
nevil 2010-03-05
  • 打赏
  • 举报
回复
sed -n 'n;p' file是打印偶数行,sed -n 'p;n' file是打印奇数行.\

现在你没有加-n参数,所以sed会先把这一行打出来,再分析是这一行奇数行还是偶数行决定是否再打一次

所以sed 'p;N' data做如下分析
The first meeting is the Linux System <===输出第一行
The first meeting is the Linux System <===第一行是奇数行,打印
Administrator's group will be held on Tudesday. <====输出第二行
All System Administrators should attend this meeting. <====输出第三行
All System Administrators should attend this meeting. <===第三行是奇数行,打印

23,129

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧