Overview and operation examples of sed editor in Linux

sed editor

Sed is a stream editor, the stream editor will edit the data stream based on a set of rules provided in advance before the editor processes the data.

The sed editor can process the data in the data stream according to commands, which are either entered from the command line or stored in a command text file.

(1) Working principle and process

The workflow of sed mainly includes three processes of reading, executing and displaying:

  • Read: sed reads a line of content from the input stream (file, pipe, standard input) and stores it in a temporary buffer (also known as pattern space).
  • Execution: By default, all sed commands are executed sequentially in the pattern space. Unless the address of the line is specified, the sed command will be executed sequentially on all lines.
  • Display: Send the modified content to the output stream. After sending the data, the pattern space will be emptied. Before all file contents are processed, the above process will be repeated until all contents are processed.
  • Before all file contents are processed, the above process will be repeated until all contents are processed.

Note: By default, all sed commands are executed in the pattern space, so the input file will not change in any way, unless redirection is used to store the output.

(2) Command usage

Command format:

sed -e '操作' 文件1 文件2 ...
sed -n -e '操作' 文件1 文件2 ...
sed -f 脚本文件 文件1 文件2 ...
sed -i -e '操作' 文件1 文件2 ...

常用选项:
-e:表示用指定命令来处理输入的文本文件,只有一个操作命令时可省略,一般在执行多个操作命令使用
-f:表示用指定的脚本文件来处理输入的文本文件。
-h:显示帮助。
-n:禁止sed编辑器输出,但可以与p命令一起使用完成输出。
-i:直接修改目标文本文件。

常用操作:
s:替换,替换指定字符。
d:删除,删除选定的行。
a:增加,在当前行下面增加一行指定内容。
i:插入,在选定行上面插入一行指定内容。
c:替换,将选定行替换为指定内容。
y:字符转换,转换前后的字符长度必须相同。
p:打印,如果同时指定行,表示打印指定行;如果不指定行,则表示打印所有内容;如果有非打印字符,则以 ASCII 码输出。其通常与“-n”选项一起使用。
=:打印行号。
l:打印数据流中的文本和不可打印的ASCII字符(比如结束符$、制表符\t)

Example:

sed -n -e 'p' 文件名    ##打印当前文件所有内容

Insert picture description here

sed -n -e '=' 文件名    ##打印文件内容行数

Insert picture description here

sed -n '
> =
> p
> ' 文件名

Insert picture description here

(3) Examples of using addresses

The sed editor has 2 addressing modes:

  • Represent the row interval in numeric form

  • Use text mode to filter out lines

Example:
Insert picture description here

(4) Delete row instance

Insert picture description here

(5) Examples of replacement content

行范围 s/旧字符串/新字符串/替换标记

4种替换标记:
数字:表明新字符串将替换第几处匹配的地方
g:表明新字符串将会替换所有匹配的地方
p:打印与替换命令匹配的行,与-n一起使用
w 文件:将替换的结果写到文件中

Insert picture description here

(6) Insert an example

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51468875/article/details/111797590