一、sed命令定义
sed编辑器被称为流编辑器,和普通的交互式编辑器相反,在交互式编辑器中,可以用键盘命令来交换的插入、删除或替换数据中的文本。流编辑器则会在编辑器处理数据之前基于预先提供的一组规则来编辑数据流。
二、sed使用格式及常用选项
sed options script file
-e script 在处理输入时,将script中指定的命令添加到运行的命令中
-f file 在处理输入时,将file中指定的命令添加到运行的命令中
-n 使用安静模式,只显示sed处理过的行
1、在命令行定义编辑命令
[root@super test]# echo This is a dog | sed 's/dog/big test/'
This is a big test
[root@super test]# cat data
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
[root@super test]# sed 's/dog/cat/' data
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy cat.
2.在命令行使用多个编辑器命令(要使用-e选项)
[root@super test]# sed -e 's/brown/green/; s/dog/cat/' data
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
The quick green fox jumps over the lazy cat.
3.从文件中读取编辑器命令(使用-f选项)
[root@super test]# cat script.sed
s/brown/green/
s/fox/elephant/
s/dog/cat/
[root@super test]# sed -f script.sed data
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
The quick green elephant jumps over the lazy cat.
4.使用地址
默认情况下,在sed编辑器中使用的命令会作用于文本数据的所有行。如果只想作用于特定的某行,就需要使用行寻址
在sed编辑器中有两种形式的行寻址:
(1)行的数字范围
(2)用文本模式来过滤出某行
数字方式寻址:
[root@super test]# sed '2s/dog/cat/' data
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
删除行:
[root@super test]# cat data1
line1
line2
line3
line4
[root@super test]# sed '3d' data1
line1
line2
line4
向文件写入:
[root@super test]# sed '1,3w test' data1
line1
line2
line3
line4
[root@super test]# cat test
line1
line2
line3
向文件读取数据:
[root@super test]# sed '3r data' data1
line1
line2
line3
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
line4
阅读(1466) | 评论(0) | 转发(0) |