老男孩教育专注IT教育10余年,只培养IT技术精英

全国免费咨询电话(渠道合作):400-609-2893

三剑客-sed执行流程是怎样的?老男孩Linux培训班

老男孩IT教育

技术博客

2020年11月11日 11:47

老男孩Linux云计算运维培训班学习,Linux三剑客学习过程中,sed执行流程是怎样的?

一. 简易流程

1.读取文件(从文件或管道)的第1行
2.读取到sed使用的内存区域中(模式空间)
3.进行判断这一行是否是我要的

1.如果是则则执行对应的命令(p d c a i s )
2.如果不是则读取下一行(注如果没加上-n sed会默认显示这行内容(模式空间内容))

二.详细执行过程

详细过程一定要看官方的说明:info sed

sed' maintains two data buffers: the active *pattern* space, and the auxiliary *hold* space. Both are initially empty. ¨K10K sed' operates by performing the following cycle on each line of
input:

sed命令的执行过程(一个循环过程)如下所示:

first, sed' reads one line from the input stream, removes any trailing newline, and places it in the pattern space. ¨K14K Then commands are executed; each command can have an address associated to it:addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to be executed. ¨K16K When the end of the script is reached, unless the-n' option is in
use, the contents of pattern space are printed out to the output
stream, adding back the trailing newline if it was removed.(1) Then the
next cycle starts for the next input line.

第3步,当命令执行完成(这里命令指的是sed内部的p d s c a i 等等),如果没有-n参数(取消sed命令默认输出)则sed会把当前模式空间的内容显示出来然后再加上1个回车(第1步被删除的).然后开始读取下一行,进行下一个循环.

Unless special commands (like D') are used, the pattern space is deleted between two cycles. The hold space, on the other hand, keeps its data between cycles (see commandsh', H',x', g',G' to move
data between both buffers).

补充说明:

模式空间的内容会在每个循环结束后清空(除非加上D)。
保持空间的内容会在每次循环之间保留不被清空 (通过 h H x g G 移动保持空间和模式空间的数据)

(1) Actually, if sed' prints a line without the terminating newline, it will nevertheless print the missing newline as soon as more text is sent to the same output stream, which gives the "least expected surprise" even though it does not make commands like `sed -n p' exactly identical to cat'.

实际上,sed如果显示没有回车的行,他会在你多次显示到相同输出的时候替你加上缺少的回车。这个特点sed -n p 和cat并不完全相同.
这算是极特殊用法了,了解即可.

[root@oldboyedu-show01 ~]# cat old.txt   #这个文件就没有回车
oldboy[root@oldboyedu-show01 ~]# 

[root@oldboyedu-show01 ~]# sed -n p  old.txt   #通过sed显示的时候 没有显示每行的结尾
oldboy[root@oldboyedu-show01 ~]# 

[root@oldboyedu-show01 ~]# sed -n p  old.txt old.txt old.txt   #多次输出的时候sed会自动加上 回车
oldboy
oldboy
oldboy[root@oldboyedu-show01 ~]# 

[root@oldboyedu-show01 ~]# cat old.txt old.txt old.txt  #同样输出到相同的地方(屏幕) cat不会自动加上回车
oldboyoldboyoldboy[root@oldboyedu-show01 ~]# 

 

阅读更多:

Cookie有哪些安全属性?网络安全培训哪家强

Token和cookie有什么区别?网络安全工程师学习知识

Linux系统初始化环境后需要做什么?浙江温州培训linux哪个好

HTTP协议请求工作流程是什么?linux运维培训机构

MySQL数据库优势特点是什么?mysql数据库DBA培训

本文经授权发布,不代表老男孩教育立场。如若转载请联系原作者。