SED
sed (Stream Editor): #
文本流编辑,是一个"非交互式的"面向字符流的编辑器。能同时处理多个文件多行内容,可以不对源文件改动,把整个文件输入到屏幕,可以把只匹配到模式的内容输出到屏幕上。还可以对源文件改动,但是不会在屏幕上返回结果。
一.语法格式: #
二.常用选项: #
option | describe |
---|---|
-n, –quiet, –silent | suppress automatic printing of pattern space |
-e script, –expression=script | add the script to the commands to be executed |
-r, –regexp-extended | use extended regular expressions in the script. |
-f script-file, –file=script-file | add the contents of script-file to the commands to be executed |
–follow-symlinks | follow symlinks when processing in place |
-i[SUFFIX], –in-place[=SUFFIX] | edit files in place (makes backup if SUFFIX supplied) |
-c, –copy | use copy instead of rename when shuffling files in -i mode |
-s, –separate | consider files as separate rather than as a single continuous long stream. |
-z, –null-data | separate lines by NUL characters |
–version | output version information and exit |
… | … |
三.地址匹配: #
Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address
ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched.
After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match.
pattern | describe |
---|---|
first~step | Match every step’th line starting with line first |
$ | Match the last line. |
/regexp/ | Match lines matching the regular expression regexp. |
\cregexpc | Match lines matching the regular expression regexp. The c may be any character. |
0,addr2 | Start out in “matched first address” state, until addr2 is found. |
addr1,+N | Will match addr1 and the N lines following addr1. |
addr1,~N | Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N. |
三.文件处理: #
四.高级使用: #
简介 #
sed 中除了有模式空间之外,还有一个叫(hold space)的保留空间,用来暂存遍历行过程中的数据。以便对sed进行更加灵活控制。 参考.使用语法如下:
cmd func d Delete pattern space. Start next cycle. 删除pattern space的内容,开始下一个循环. h、 H Copy/append pattern space to hold space. 复制/追加pattern space的内容到hold space. g、 G Copy/append hold space to pattern space. 复制/追加hold space的内容到pattern space. x Exchange the contents of the hold and pattern spaces. 交换hold space和pattern space的内容. 操作 #
流程演示 #