正则表达式3
sed
cat -n test | sed '/good/ a this is append by good!'
cat -n test | sed '/good/ i this line is insert by bood'
sed -n '2,/is/'p test 显示出匹配到的内容
sed -n '/good/=' test 打印出匹配到good的行号
如果需要对同一文件或同一行进行多次修改,可以有三种方法
实操
第一种
sed -n -e '/glad/=' -e '/glad/p' test 同时打印出匹配到的glad行号和内容
第二种
sed '/glad/=;/glad/p' test 效果同上
第三种
sed -n '
>/glad/=
>/glad/p' test
效果同上
替换操作
sed -e 's/is/IS/' -e 's/am/WAS/' test 同时将所有的is替换为大写is,将am替换为WAS
sed 's/is/IS/g;s/am/WAS/' test 效果同上
sed '
>s/is/IS/g
>s/am/WAS/' test
创建sed脚本
实操
tmp目录下新建一个tst.sed文件
vi tst.sed
#!/bin/sed -f
/good/ a\
this line is append by good
保存退出
然后给tst.sed 赋予可执行权限
chmod u+x tst.sed
./tst.sed test 执行脚本对test文件操作,返回正确结果
脚本插入操作
vi tst.sed
将之前内容注释掉
写入
/sbin/ i this line is insert by sbin
保存退出
./tst.sed test 执行插入操作,返回正确结果
或执行
sed -f tst.sed test 效果和./tst.sed test 一样
将之前tst.sed中注释的内容解除注释仍可以执行脚本
替换问题
实操
sed 's/is/IS/gw test' test 这里w参数的作用是将团替换的结果输出到test文件中,改变了test文件
图中列举了所有的sed相关参数功能,其它未用到的参数可自行测试和练习