sed的特点:
sed同awk一样都是行处理器,不过不同的是awk针对记录进行分割显示,而sed则主要用于对记录进行修改
sed使用场景
替换关键字,例如在redis部署中,如果需要部署多个redis实例,则需要根据端口创建不同的配置文件,我们则可以这样做:
sed ‘s#6379#6380#g’ 6379.conf > 6380.conf
通过以下shell命令可以实现一次生成多个配置文件:
for port in $(seq 6380 6385); do sed ‘s#6379#${port}#g’ 6379.conf > ${port}.conf; done;
sed命令详解:
命令参数:
- 取消默认输出参数:-n
- 连续编辑参数:-e
- 将修改作用到文件参数:-i
命令选项:
打印信息选项:p
打印包含root到包含mysql范围的所有行:
sed -n ‘/root/,/mysql/p’ test.txt
打印行号:=
打印包含root到包含mysql范围的所有行的行号:
sed ‘/root/,/mysql/=’ test.txt
行追加选项:a
在第一行行追加hello wold字符串
sed ‘1a hello world’ test.txt
在第一行到第三行每行后面追加hello world字符串
sed ‘1,3a hello world’ test.txt
在第三行到最后一行每行后面追加hello world字符串
sed ‘3,$a hello world’ test.txt
行插入选项:i
在包含mysql的行到最后一行的每行前插入hello world字符串
sed ‘/mysql/,$i hello world’ test.txt
在第三行到包含mysql的行的每行前插入hello world字符串
sed ‘3,/mysql/i hello world’ test.txt
在包含root到包含mysql范围的每行前插入hello world字符串
sed ‘/root/,/mysql/i hello world’ test.txt
行替换选项:c
除第3行到第5行的其他替换为hello world字符串
sed ‘3,5!c hello world’ test.txt
将包含bash的行替换为hello world字符串
sed ‘/bash/c hello world’ test.txt
行删除选项:d
删除包含nologin的行:
sed ‘/nologin/d’ test.txt
删除空行:
sed ‘/^$/d’ test.txt
删除以数字开头的行:
sed ‘/^[0-9][0-9]*/d’ test.txt
删除以字母结尾的行:
sed ‘/^[A-Z a-z][A-Z a-z]*/d’ test.txt
全局选项:g
替换字符串选项:s
替换mysql为oracle:
sed ‘s/mysql/oracle/g’ test.txt
替换多个空格为一个空格:
sed ‘s/[ ][ ]*/ /g’ netstat.txt
如果空格与TAB共存时用下面的命令进行替换:
sed ‘s/[[:space:]][[:space:]]*/ /g’ netstat.txt
sed中( )和\1的功能:
- 打印ifconfig中的IP地址
ifconfig | sed -n ‘s#^.*inet (.*) netmask.*$#\1#gp’
或者
ifconfig | sed -n ‘s#^.*inet[ ]*(.*)[ ]*netmask.*$#\1#gp’
或者(该命令不显示本地的127.0.0.1地址)
上述选项中匹配行的方式可以相互使用
更多问题可以加公众号:代码小栈,期待为您解决更多问题