百度云盘容量:sed?基础,语句格式

来源:百度文库 编辑:偶看新闻 时间:2024/05/09 12:01:04
sed 基础,语句格式
(2009-08-11 03:17:05)转载
标签:sed
-n
单引号扩展

杂谈
分类:perl,cgi,shell脚本编程
Sed是一个基本的“查找(pattern)+处理(command)”程序
sed '/pattern/command ' file
regex pattern:国际标准正则式,比如CISCO AS-PATH也采用国际标准正则式
/pattern/后跟命令如d(删除),G(加空行)等
/pattern/最简单的匹配---包含匹配-----类似grep
Sed和grep原理比较相似,根本不是精确匹配,所以没有通配符,*没什么用
[root@machome macg]# sed '/111/G' 111.txt 在包含111的行后加一个空行
this is 111file
this is 222file
this is 333file
[root@machome macg]# sed '/222/d' 111.txt 删除所有包含222的行
this is 111file
this is 333file
[]匹配一个指定范围内的字符,
如: /[Ss]ed/ 匹配sed和Sed。
$——匹配末尾行的pattern
sed '/^$/d' 111.txt
删掉空行,^$表示空行
$ sed -n '$p' 111.txt
disable=no
显示最后一行
(p自然要和-n合用,否则全显示,就没意义了)
Sed command file ——没有/pattern/,就是针对所有行,每一行
Sed G 111.txt 对文件的所有行,都加一空行
如果没有pattern, 且只有一条命令,可以去掉’ ‘
!command ——不匹配,不是设在pattern内,而是pattern外的command上
$ sed -n '/disable/!p' 111.txt
显示不匹配/pattern/的行
sed '/baz/!s/foo/bar/g不含有/pattern/的行,进行foo到bar的s替换
‘numcommand’ /pattern/的替代品,匹配行号
Sed ‘3a\\…’ 匹配行号并追加
SED和AWK,GREP一样,最后一个参数是file,显然可以和任何指令进行管道连接
command | sed '描述串' Command > tmp
Sed ‘ prog’ tmp
sed只改变输出,不改变实际文件
[root@machome macg]# more 111.txt
this is 111file
this is 111file
this is 111file
this is 111file
this is 111file
[root@machome macg]# sed G 111.txt 在每一行后面增加一空行后输出
this is 111file
this is 111file
this is 111file
this is 111file
this is 111file
[root@machome macg]# more 111.txt 实际文件没变
this is 111file
this is 111file
this is 111file
this is 111file
this is 111file
sed > file 实际改文件,输出重定向
[root@machome macg]# sed G 111.txt >111-tmp.txt
sed的p(显示)是基于显示整个文件的基础上,其实没什么用,无法“只显示”
$ sed '/echo/p' ttt1 显示含有echo的行
test()
{
GONE="(ServerType
GONE="${GONE}AgentLog 结果显示所有行
echo $GONE 并且把含有echo的行显示两遍
echo $GONE
}
sed –n p 解决sed p命令无法“只显示匹配行”的缺陷的两大办法
echo $i sed –n法
$ sed -n '/echo/p' ttt1
echo echo echo $GONE
echo input:
所以sed的p命令都是和sed –n一起用的 sed !d法
sed !d法,不匹配的行都删掉,同时sed会自动显示结果(即匹配的行)
$ sed '/echo/!d' ttt1
echo echo echo $GONE
echo input:
sed –n 起“只”的作用
不加-n 的sed也是非常有用的,主要用于/xxx/d s/xxx/yyy和a/xxx/yyy等需要修改的地方
这样输出的是修改过的整个文件,而不只是修改过的某行。
实际sed –n多数只用于p(显示)或=(显示行号)等类似grep的显示用途。
sed -n '/disable/p' 111.txt
sed –n ‘=’
sed 的单引号’ ‘加不加均可
$ sed '/^$/d' 111-tmp.txt
this is 111file
this is 111file
this is 111file
this is 111file
$ sed /^$/d 111-tmp.txt
this is 111file
this is 111file
this is 111file
this is 111file
$ sed '1,10d' 111-tmp.txt
that is 111file
$ sed 1,10d 111-tmp.txt
that is 111file
但还是建议加’ ‘ 因为有时有没有引号,系统会做不同处理
$ sed 's/^/\t/' ttt1
文件头加TAB
test()
{
GONE="(ServerType
$ sed s/^/\t/ ttt1
文件头加t,就是没引号造成的
t test()
t {
t GONE="(ServerType