sed命令
流编辑器,与vi同源:用于文件的行级处理
一.sed命令格式:
1.sed 选项 ‘脚本语句(/pattern/action)’ 待操作文件
2.sed 选项 -f ‘脚本文件’ 待操作文件
pattern为正则表达式,action为动作
二.常用选项
-i[SUFFIX], 就地编辑文件,如果提供后缀,则进行备份
-n, --quiet, --silent 取消自动打印模式空间(静默输出,不会输出整个文件)
-r, --regexp-extended 在脚本中使用扩展正则表达式
三.常用动作
a,append 追加
i,insert 插入
d,delete 删除
s,substitution 替换
四.常用脚本语句
/pattern/p 打印匹配pattern的行
/pattern/d 删除匹配pattern的行
五.使用实例
1.追加
(1)在sedtest.sh第4行后追加xxxxxxxxxxxxxxxxxxxx;只反映到终端输出,但不修改源文件
[root@localhost sed]# sed “4a xxxxxxxxxxxxxxxxxxxx” sedtest.sh
(2)在sedtest.sh第4行后追加xxxxxxxxxxxxxxxxxxxx;修改到源文件
[root@localhost sed]# sed -i “4a xxxxxxxxxxxxxxxxxxxx” sedtest.sh
2.插入
在sedtest.sh第4行前插入yyyyyyyyyyyyyyyyyyyy;修改到源文件
[root@localhost sed]# sed -i “4i yyyyyyyyyyyyyyyyyyyy” sedtest.sh
3.删除
删除sedtest.sh第2-7行;修改到源文件
[root@localhost sed]# sed “2,7d” sedtest.sh -i
4.替换
将sedtest.sh中的所有echo替换成printf;修改到源文件
[root@localhost sed]# sed ‘/s/echo/printf/g’ sedtest.sh -i
5.使用扩展正则表达式(小括号不需要转义)
[root@localhost sed]# sed -r “s/([0-9])([0-9])/=\1==\2=/g” sedtest.sh
6.同时执行多条正则
(1)使用分号分隔多条正则
[root@localhost sed]# sed “s/echo/printf/;s/yes/good/” sedtest.sh
(2)使用-e添加多条正则
[root@localhost sed]# sed -e “s/echo/printf/” -e “s/yes/good/” sedtest.sh
7.截取html文件中<>以外的内容
[root@localhost sed]# cat sedtest.html
<html><head><title>Hello world</title></head>
<body>welcome to the world of regexp</body></html>
[root@localhost sed]# sed “s/<[^<>]*>//g” sedtest.html
Hello world
welcome to the world of regexp
sed命令的帮助信息 参考翻译
[root@localhost sed]# sed --help
用法: sed [选项]… {脚本(如果没有其他脚本)} [输入文件]…
-n, --quiet, --silent
取消自动打印模式空间
-e 脚本, --expression=脚本
添加“脚本”到程序的运行列表
-f 脚本文件, --file=脚本文件
添加“脚本文件”到程序的运行列表
–follow-symlinks
直接修改文件时跟随软链接
-i[SUFFIX], --in-place[=SUFFIX]
就地编辑文件(如果提供后缀则进行备份)
-c, --copy
在-i模式下移动文件时,使用copy而不是重命名
-b, --binary
不进行任何操作;兼容WIN32/CYGWIN/MSDOS/EMX (以二进制模式打开文件(CR+LFs不进行特殊处理)
-l N, --line-length=N
指定“l”命令的换行期望长度
–posix
关闭所有 GNU 扩展
-r, --regexp-extended
在脚本中使用扩展正则表达式
-s, --separate
将输入文件视为各个独立的文件而不是一个长的连续输入
-u, --unbuffered
从输入文件读取最少的数据,更频繁的刷新输出
-z, --null-data
用NUL字符分隔行
–help
显示此帮助并退出
–version
输出版本信息并退出
如果没有 -e, --expression, -f 或 --file 选项,那么第一个非选项参数被视为
sed脚本。其他非选项参数被视为输入文件,如果没有输入文件,那么程序将从标准输入读取数据。