#例子4 [root@localhost ~]# cat sed_script.txt #编辑命令存放的文本文件 1d 10d [root@localhost ~]# sed -f sed_script.txt poetry 2)Never lose hope. 3)Always have faith, 4)It allows you to cope. 5)Trying times will pass, 6)As they always do. 7)Just have patience, 8)Your dreams will come true. 9)So put on a smile, 11)Know it will pass, 12)And strength you will gain
我们可以看到例子4中sed使用-f选项指定编辑命令所在的文件,执行的是和例子3同样的操作,删除第一行和第十行,当我们得编辑命令有很多,把它放在文件也是一个不错的做法吧!
行定界默认情况下不指定行的定界,会读取处理整个文件的每一行。如果指定了行,还是会读取每一行,但是在执行各种命令操作之后,会进行判断是不是定界的行,如果判断成功,则执行操作,如删除行,如果判断失败,则不做任何的处理然后打印至标准输出,下面来看一下几种常见的定界方法:
(1)定界为空,对全文的每一行进行处理
[root@localhost ~]# sed '' poetry 1)Never give up, 2)Never lose hope. 3)Always have faith, 4)It allows you to cope. 5)Trying times will pass, 6)As they always do. 7)Just have patience, 8)Your dreams will come true. 9)So put on a smile, 10)You'll live through your pain. 11)Know it will pass, 12)And strength you will gain
(2)单行指定
a.直接写单个数字,表示指定行
[root@localhost ~]# sed '2d' poetry #当判断为第二行的时候,会删除第二行 1)Never give up, 3)Always have faith, 4)It allows you to cope. 5)Trying times will pass, 6)As they always do. 7)Just have patience, 8)Your dreams will come true. 9)So put on a smile, 10)You'll live through your pain. 11)Know it will pass, 12)And strength you will gain
b./pattern/:被模式匹配到的行,默认可以是基本的正在表达式
[root@localhost ~]# sed '/As/ d' poetry #删除被模式匹配的行 1)Never give up, 2)Never lose hope. 3)Always have faith, 4)It allows you to cope. 5)Trying times will pass, 7)Just have patience, 8)Your dreams will come true. 9)So put on a smile, 10)You'll live through your pain. 11)Know it will pass, 12)And strength you will gain
c.$最后一行
[root@localhost ~]# sed '$ d' poetry #删除最后一行 1)Never give up, 2)Never lose hope. 3)Always have faith, 4)It allows you to cope. 5)Trying times will pass, 6)As they always do. 7)Just have patience, 8)Your dreams will come true. 9)So put on a smile, 10)You'll live through your pain. 11)Know it will pass,
(3)定界范围
a.x,y:x至y行
[root@localhost ~]# sed '1,9 d' poetry #删除了1-9行 10)You'll live through your pain. 11)Know it will pass, 12)And strength you will gain
b.x,+y:x行到,x行往下数y个行