Sed
Sed是一个强大的文本处理工具
可以采用正则匹配,对文本进行插入删除修改等操作
Sed处理的时候,一次处理一行,每一次把当前处理的存放在临时缓冲区,处理完后输出缓冲区内容到屏幕,然后把下一行读入缓冲区,如此重复,直到结尾。
1、命令格式和参数
sed [-nefr] [动作] 文件
参数:
-n 安静模式,在sed处理的时候,所有来自STDIN的数据都会被输出到终端,加上-n会只输出处理的哪行
-e 直接在命令列上进行sed动作编辑
-f 直接将sed的动作写在文件内
-r sed动作支持延伸的正则表达(默认只是基础正则)
-i 直接修改文件内容(慎用,尤其是用系统文件做练习的时候)
动作:
a append:增加,在当前行的下一行增加
c :取代,取代n1到n2之间的行
d delete:删除
i 插入,目前行的上一行插入
p 打印,常常与-n使用
s 取代,s/old/new/g
2、基础用法详解
(1)第一行之后添加一行
(2)第一行之前添加一行
(3)删除第2,3行
(4)打印第2,3行
这里要提到的是,尽量使用-n,不然会出现这样的结果
(5)把168换成169
先看源文件
处理后
(6)插入多行
(7)匹配数据,然后进行操作
只需要在上述的基础上加上正则匹配
sed "/匹配的模式/处理的方式" file.txt
sed "/^root/d" file.txt 对开始有root的删除
例如
匹配begin,并删除改行
匹配123,并且把含有123的行162都替换成172
这里大括号{}里可以执行多个命令,用;隔开即可,q是退出
(8)连续编辑 -e
删除第二行,并且匹配把last替换成new
(9)直接修改文件,切记不要修改系统文件
三 、一个比较有趣的例子
如何替换\n也就是把所有的行都归为一行
第一种方式
Sed是一个强大的文本处理工具
可以采用正则匹配,对文本进行插入删除修改等操作
Sed处理的时候,一次处理一行,每一次把当前处理的存放在临时缓冲区,处理完后输出缓冲区内容到屏幕,然后把下一行读入缓冲区,如此重复,直到结尾。
1、命令格式和参数
sed [-nefr] [动作] 文件
参数:
-n 安静模式,在sed处理的时候,所有来自STDIN的数据都会被输出到终端,加上-n会只输出处理的哪行
-e 直接在命令列上进行sed动作编辑
-f 直接将sed的动作写在文件内
-r sed动作支持延伸的正则表达(默认只是基础正则)
-i 直接修改文件内容(慎用,尤其是用系统文件做练习的时候)
动作:
a append:增加,在当前行的下一行增加
c :取代,取代n1到n2之间的行
d delete:删除
i 插入,目前行的上一行插入
p 打印,常常与-n使用
s 取代,s/old/new/g
2、基础用法详解
(1)第一行之后添加一行
(2)第一行之前添加一行
(3)删除第2,3行
(4)打印第2,3行
这里要提到的是,尽量使用-n,不然会出现这样的结果
(5)把168换成169
先看源文件
处理后
(6)插入多行
(7)匹配数据,然后进行操作
只需要在上述的基础上加上正则匹配
sed "/匹配的模式/处理的方式" file.txt
sed "/^root/d" file.txt 对开始有root的删除
例如
匹配begin,并删除改行
匹配123,并且把含有123的行162都替换成172
这里大括号{}里可以执行多个命令,用;隔开即可,q是退出
(8)连续编辑 -e
删除第二行,并且匹配把last替换成new
(9)直接修改文件,切记不要修改系统文件
三 、一个比较有趣的例子
如何替换\n也就是把所有的行都归为一行
第一种方式
第二种方式