欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sed指令讲解和常见用法

程序员文章站 2022-06-18 23:18:43
...

在linux环境下,sed是一种非常常用的非交互式的流编辑器。流编辑器就是针对输入流进行编辑,输出到输出流。

sed的具体工作流程

首先需要明确两点:

  1. sed认不改变输入流
  2. sed基本处理单位是行

具体的流程为:

sed从输入流中读取一行,放到pattern space这个缓存区,执行相应的命令,执行完命令,放入hold space中,作为输出流,输出到目录,或者重定向到文件,开始读取下一行。

sed的基本指令模式

sed 【动作修饰】【动作】

动作修饰用来指定后面所有执行的动作的一些行为模式,如下:

# -n: 安静模式,只有真正执行动作的目标行才会被输出;相对的,非安静模式,所有输入都会输出
[[email protected] sed]$ for i in {1..10}; do echo line:$i >> 1.txt; done
[[email protected] sed]$ vi 1.txt 
[[email protected] sed]$ sed -n '1p' 1.txt 
line:1

# -e: 直接指定命令,可以同时指定多个sed命令,而命令们顺序执行
[[email protected] sed]$ cat 1.txt | sed  -e 's/line/Line/' -e '/Line:1$/a helloworld'
Line:1
helloworld
Line:2
Line:3
Line:4
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10

# -f: 指定将命令写到一个文件内或者执行文件内的sed命令
[[email protected] sed]$ cat test.sed 
#!/bin/sed -f
1p
2,3s/line/Line/g
[[email protected] sed]$ cat 1.txt | sed -f test.sed 
line:1
line:1
Line:2
Line:3
line:4
line:5
line:6
line:7
line:8
line:9
line:10

# -r: 延伸型正则表达式
# 略

# -i: 直接修改读取的文件内容,而不输入到终端
[[email protected] sed]$ sed -i "s/line/Line/g" 1.txt 
[[email protected] sed]$ cat 1.txt 
Line:1
Line:2
Line:3
Line:4
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10

动作模式通常为:位置符号动作,如下

#[1,2p][a c d i p s]
[[email protected] sed]$ cat 1.txt | sed  '1a test'
Line:1
test
Line:2
Line:3
Line:4
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10
[[email protected] sed]$ cat 1.txt | sed  '2,4c test'
Line:1
test
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10
[[email protected] sed]$ cat 1.txt | sed  '2,4d'
Line:1
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10
[[email protected] sed]$ cat 1.txt | sed  '2i helloworld'
Line:1
helloworld
Line:2
Line:3
Line:4
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10
[[email protected] sed]$ cat 1.txt | sed  -n '2p'
Line:2
[[email protected] sed]$ cat 1.txt | sed   '2,3s/Line/line/g'
Line:1
line:2
line:3
Line:4
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10

至于其他的高级用法,可参考:https://blog.csdn.net/u012759878/article/details/48908989

 

相关标签: sed linux sed