sed指令讲解和常见用法
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
免费下载资源
·
在linux环境下,sed是一种非常常用的非交互式的流编辑器。流编辑器就是针对输入流进行编辑,输出到输出流。
sed的具体工作流程
首先需要明确两点:
- sed认不改变输入流
- sed基本处理单位是行
具体的流程为:
sed从输入流中读取一行,放到pattern space这个缓存区,执行相应的命令,执行完命令,放入hold space中,作为输出流,输出到目录,或者重定向到文件,开始读取下一行。
sed的基本指令模式
sed 【动作修饰】【动作】
动作修饰用来指定后面所有执行的动作的一些行为模式,如下:
# -n: 安静模式,只有真正执行动作的目标行才会被输出;相对的,非安静模式,所有输入都会输出
[wlin@wlin sed]$ for i in {1..10}; do echo line:$i >> 1.txt; done
[wlin@wlin sed]$ vi 1.txt
[wlin@wlin sed]$ sed -n '1p' 1.txt
line:1
# -e: 直接指定命令,可以同时指定多个sed命令,而命令们顺序执行
[wlin@wlin 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命令
[wlin@wlin sed]$ cat test.sed
#!/bin/sed -f
1p
2,3s/line/Line/g
[wlin@wlin 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: 直接修改读取的文件内容,而不输入到终端
[wlin@wlin sed]$ sed -i "s/line/Line/g" 1.txt
[wlin@wlin 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]
[wlin@wlin 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
[wlin@wlin sed]$ cat 1.txt | sed '2,4c test'
Line:1
test
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10
[wlin@wlin sed]$ cat 1.txt | sed '2,4d'
Line:1
Line:5
Line:6
Line:7
Line:8
Line:9
Line:10
[wlin@wlin 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
[wlin@wlin sed]$ cat 1.txt | sed -n '2p'
Line:2
[wlin@wlin 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
GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e
added ecosystem file for PM2 4 年前
5def40a3
Add host customization support for the NodeJS version 4 年前
更多推荐
已为社区贡献1条内容
所有评论(0)