- sed意为“流编辑器(stream editor)”
字符串筛选工具。- 对一个文档中的行进行操作
和vi编辑很相似。可以查看vim使用命令详解
1 sed基本格式
第一种
sed 参数 '脚本语句(/pattern/action)' 待操作文件
第二种
sed 参数 -f '脚本文件' 待操作文件
参数
sed参数
a 追加append
i 插入insert
d 删除delete
s替换substitution
$ cat seqtest
#! /bin/sh
echo "Enter a Yes or no"
read BUF
case "$BUF" in
yes |Y|y|YES|Yes)
echo "It's a yes.";;
[nN]?)
echo "It's a NO.";;
*)
echo "other case.";;
esac
echo "gong to return"
return 0
echo "going to return end"
2 行追加a
追加到后面
$ sed '4a this is an added line' seqtest
执行上面命令后,只会屏幕上输出,而不会保存到文件中
$ sed '4a this is an added line' seqtest
#! /bin/sh
echo "Enter a Yes or no"
read BUF
this is an added line
case "$BUF" in
yes |Y|y|YES|Yes)
echo "It's a yes.";;
[nN]?)
echo "It's a NO.";;
*)
echo "other case.";;
esac
echo "gong to return"
return 0
echo "going to return end"
如果想要保存那就需要加一个参数-i
$ sed -i '4a this is an added line' seqtest
$ cat seqtest
#! /bin/sh
echo "Enter a Yes or no"
read BUF
this is an added line
case "$BUF" in
yes |Y|y|YES|Yes)
echo "It's a yes.";;
[nN]?)
echo "It's a NO.";;
*)
echo "other case.";;
esac
echo "gong to return"
return 0
echo "going to return end"
3 删除某行
$ sed '5d' seqtest
#! /bin/sh
echo "Enter a Yes or no"
read BUF
case "$BUF" in
yes |Y|y|YES|Yes)
echo "It's a yes.";;
[nN]?)
echo "It's a NO.";;
*)
echo "other case.";;
esac
echo "gong to return"
return 0
echo "going to return end"
4 插入某行 和a用法一样,只是追加到行前
5 替换命令s
r$ sed 's/BUF/buffer/g' seqtest
#! /bin/sh
echo "Enter a Yes or no"
read buffer
this is an added line
case "$buffer" in
yes |Y|y|YES|Yes)
echo "It's a yes.";;
[nN]?)
echo "It's a NO.";;
*)
echo "other case.";;
esac
echo "gong to return"
return 0
echo "going to return end"
6常用sed命令
6.1打印包含特定字符的行
相当于grep命令
$ sed -n '/BUF/p' seqtest
read BUF
case "$BUF" in
如果不加-n是下面输出
$ sed '/BUF/p' seqtest
#! /bin/sh
echo "Enter a Yes or no"
read BUF
read BUF
this is an added line
case "$BUF" in
case "$BUF" in
yes |Y|y|YES|Yes)
echo "It's a yes.";;
[nN]?)
echo "It's a NO.";;
*)
echo "other case.";;
esac
echo "gong to return"
return 0
echo "going to return end"
6.2 某字符的特殊模式
$ sed 's/BUF/-$-/g' seqtest
#! /bin/sh
echo "Enter a Yes or no"
read -$-
this is an added line
case "$-$-" in
yes |Y|y|YES|Yes)
echo "It's a yes.";;
[nN]?)
echo "It's a NO.";;
*)
echo "other case.";;
esac
echo "gong to return"
return 0
echo "going to return end"
7 sed扩展sed -r
和grep不同,sed用参数r进行扩展
8 sed一次指定多条不同的替换命令,用";"隔开
9 明白下面例子
$ sed 's/<[^<>*]>//g' t.html
<html><head><title>Hello World</title></head>
<body>Welcome to the world of regexp!</body></html>
$ sed 's/<[^<>]*>//g' t.html
Hello World
Welcome to the world of regexp!
网友评论