定义
sed
是流编辑器,一次解决一行内容
对文本的解决流程:(模式空间是重点)
格局:
sed [-hn][-e<script>][-f<script file>][file]
-h
:显示帮忙文档\-n
:仅显示script
解决后的后果\-e<script>
:已选项中指定的 script 来解决输出的文本文件\-f<script文件>
:已选项中指定的 script 文件来解决输出的文本文件\
罕用动作(以下动作不会扭转源文件内容)
a
:新增;sed -e '4 a newline'
:在第4行后新增一行\c
:取代;sed -e '2-5 c No 2-5 number'
\d
:删除;sed -e '2,5 d'
:删除第 2,5 行\i
:插入;sed -e '2 i newline'
:在第2行前插入一行\p
:打印;sed -n '/root/p'
:只打印蕴含 root 的行;/***/
中的内容示意正则匹配语法脚本\s
:替换;sed -e 's#old#new#g'
:将 old 替换为 new,g
代表全局替换;# 能够换成/,@
等\
实战利用
- 在第4行前面增加新字符串
$ cat testroot root hello rootrootrootleokatehogwartstringleon$ sed -e '4 a newline' testroot root hello rootrootrootleonewline # 新插入的行katehogwartstringleon
- 在第2行前增加新字符串
$ sed -e '2 i newline' testroot root hello rootnewline # 在第2行前增加rootrootleokatehogwartstringleon
- 全局替换
$ sed -e 's/root/hello/g' testhello hello hello hellohellohelloleokatehogwartstringleon
- 间接批改源文件;留神:要提前对源文件进行备份
$ sed -i 's/root/user/' test$ cat testuser root hello rootuseruserleokatehogwartstringleon
课程实战利用
- 联合
w
命令查看在线人数
w | sed '1, 2d' | awk '{print $1}' | sort | uniq -c | wc -l