sed并不真正保存文件,可以先保存在临时文件,然后拿临时文件来覆盖原文件

如果需要直接修改,加-i参数

sed 样式命令 文件

sed '3,6/p' file1              //显示3-6行

sed '3,6/!p' file1            //不显示3-6行

sed '/[0-9]\{3\}/p'          //显示有3位数字的行

sed '/^$/d'       /etc/xx.conf           //删除空行

sed '^#/d'    /etc/xx.conf              //删除注释行

sed -n                       //

sed -i '/La/aOo' file1   //查找La的行,将第一个La后增加Oo一行

sed -i '/La/iOo' file1   //查找La的行,将第一个La前增加Oo一行

sed -n 's/La/Oo/p' file1    //查找La的行,将第一个La替换为Oo

sed -n 's/La/Oo/pg' file1   //查找La的行,将所有La替换为Oo

sed 's/...$//' file1        //删除每一行的最后3个字符

sed -n '/AAA/s/234/567/p' file1  //查找包含AAA的第一行,将234替换为567

sed -n '/AAA/,/DDD/s/234/567/p' file1  //查找包含AAA到DDD的第一行,将234替换为567


sed -e  's/root/shrek/g' /etc/passwd

  //-e 表示后面接受命令,s 替换,d 删除,


-e 一行可以多个命令 比如

sed -e  '/^$/d'   -e '^#/d'       /etc/xx.conf           //删除空行

-n 默认不输出




sed -e  's/\<root\>/shrek/g' /etc/passwd  将root这个单词替换为shrek


echo 's/abc/com/g' > file

echo  's/com/org/g' >>file

sed -f file xx.conf   //-f 指定脚本文件



sed -e '/^#/d;/^$/d'  abc.conf 显示未注释行


在Sed中使用变量

一般在sed 中替换都用单引号,如下边
sed -in-place ‘s/8080/8001/g’ /home/work/server.xml
但是如果需要把8001改成变量,如
sed -in-place ’s/8080/$port/g‘ /home/work/server.xml
这样就不成功。
此时需要把单引号改成双引号,如下边例子
$port=8001
sed -in-place "s/8080/$port/g" /home/work/server.xml