关于linux:0109-Linux三剑客sed

7次阅读

共计 925 个字符,预计需要花费 3 分钟才能阅读完成。

定义

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 test
root root hello root
root
root
leo
kate
hogwart
string
leon
$ sed -e '4 a newline' test
root root hello root
root
root
leo
newline  # 新插入的行
kate
hogwart
string
leon
  • 在第 2 行前增加新字符串
$ sed -e '2 i newline' test
root root hello root
newline  # 在第 2 行前增加
root
root
leo
kate
hogwart
string
leon
  • 全局替换
$ sed -e 's/root/hello/g' test
hello hello hello hello
hello
hello
leo
kate
hogwart
string
leon
  • 间接批改源文件; 留神:要提前对源文件进行备份
$ sed -i 's/root/user/' test
$ cat test
user root hello root
user
user
leo
kate
hogwart
string
leon

课程实战利用

  • 联合 w 命令查看在线人数
w | sed '1, 2d' | awk '{print $1}' | sort | uniq -c | wc -l
正文完
 0