sed
2022-11-22
三剑客老二
特长:
取行、替换、删除、追加
简介
Sed 是 Stream Editor(字符流编辑器)的缩写,简称流编辑器。
Sed 是操作、过滤和转换文本内容的强大工具。常用功能有对文件实现快速增删改查(增加、删除、修改、查询),其中查询的功能中最常用的 2 大功能是过滤(过滤指定字符串)和取行(取出指定行)。
【语法格式】
sed [选项] [sed 内置命令字符] [输入文件]
选项:
-n # 取消默认输出;只要用-n基本上就需要带p
-i # 直接修改文件;而不是输出到终端
-r # 扩展正则
内置命令符:
s # 替换
g # 全局替换
a # 全拼append,表示追加文本,在指定行后增加一行或多行文本;
d # 全拼delete,表示匹配行的文本
i # 全拼insert,表示插入文本,在指定行前添加一行或多行文本
p # 表示打印匹配行内容,通常p会参与选项-n一起使用
s/sr/de/g # 用de替换sr部分内容
# sr部分可以使用正则,de可以使用特殊字符&和\1-\9等匹配 sr部分的内容;
使用
# -n 输出匹配行
sed -n '/test/p' /etc/passwd
test3:x:10012:10012::/home/test3:/bin/bash
# -d 删除行,不删除源文件;需要删除源文件加
sed '/test/d' /etc/passwd
sed '3d' test.txt # 删除指定行
sed '3,5d' test.txt # 删除3-5行
# -e 多次编辑
sed -e 's#a#b#g' -e 's#c#d#g' test.txt
# -a 追加;在第二行下追加
sed '2a test txt' test.txt
# -i 插入,在第二行上插入一行
sed '2i test code' test.txt
sed '2i test code\naaa\nbbb' test.txt # 插入多行
# 正则使用;获取IP地址
ifconfig eth0 | sed -nr '2s#.*net (.*) netmask.*#\1#gp'
# 获取 权限
stat .| sed -nr '4s#.*\(0(.*)/d.*#\1#gp'
# 在每行开头添加字符 HEAD
sed "s/^/HEAD&/g" test.file
# 在每行结尾添加字符 TAIl
sed "s/$/&TAIL/g" test.file
# 两条命令和起来用,在开头添加 HEAD ,结尾添加 TAIL
sed "/./{s/^/HEAD&/;s/$/&TAIL/}" test.file
匹配行 前、后 添加一行 字符串
# 在 linux 中可以,macOs 系统自己再找找方法吧。
# 匹配行后添加 一行数据:ceshi
sed -i '/aaa/a \ceshi' a
# 匹配行前添加 一行数据:ceshi
sed -i '/aaa/i \ceshi' a
# 实际使用,修改 dockerfile 的字符集
for i in $(find . -name "Dockerfile*");do sed -i '/FROM/a \ENV LANG C.UTF-8' $i;done