linux命令之sed
sed编辑器
sed编辑器被称作流编辑器(stream editor),和普通的交互式编辑器恰好相反.在交互式编辑器中,如(vim)你可以用键盘命令来交互式的插入,删除或替换数据中的文本.流编辑器则会在编辑器处理数据之前基于预先提供的一组规则来编辑数据流.
特点:
sed 编辑器可以根据命令来处理数据流中的数据,这些命令要么从命令行输入,要么存储在一个命令文本中.
执行流程
1.一次从输入中读取一行数据
2.根据所提供的编辑器命令匹配数据
3.按照命令修改流中的数据
4.将处理后的新数据输出到STDOUT
在流编辑器将所有命令与一行数据匹配完毕后,他会读取下一行数据并重复这个过程.在流编辑器处理完流中的所有数据行,他就会终止.
sed命令
sed命令的格式
sed options script file
options:
-e script 在处理输入时 将script中指定的命令添加到已有的命令中(允许执行多个命令)
-f file 在处理输入时 将file中指定的命令添加到已有的命令中
-n 不产生命令输出,使用print命令来完成输出
1)替换命令 s
s 替换命令sed 格式 sed 's/test/cat/' 第二个文本替换第一个
不添加选项
data.txt
This is a test
管道输入数据
echo "This is a test" | sed 's/test/cat/'
# This is a cat
文本输入数据
sed 's/test/cat/' data.txt
# This is a cat
在命令行使用多个编辑器命令
sed -e 's/test/cats/; s/a/two/' data.txt
# This is two cats
命令之间必须用分号(;)隔开, 且命令末尾和分号之间不能有空格.
从文件中读取编辑命令
script1.sed
s/test/cats/
s/a/two/
sed -f script1.sed data.txt
# This is two cats
2)删除(行)命令 d
sed 'd' data.txt
# 流中的所有文本行都会被删除
3)插入命令 i 和 a
echo "test line 2" | sed 'i\test line 1' 在行前插入新的一行
# test line 1
# test line 2
echo "test line 2" | sed 'a\test line 1' 在行后插入新的一行
# test line 2
# test line 1
4)修改行命令 c
echo "test line 2" | sed 'c\test line 1' 将匹配到的行修改
# test line 1
# 用string替换文本中的第一行
sed -i '1'c'string' 123.txt
5)转换命令 y
echo "this is 1 2 3" | sed 'y/123/789/' 对应位置映射转换
# this is 7 8 9
6)打印行号命令 =
echo "this is line 1" | sed '='
# 1
# this is line 1
7)列出行命令 l(L小写)
data.txt
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
sed 'l' data.txt
# 输出
this is line 1$
this is line 1
this is line 2$
this is line 2
this is line 3$
this is line 3
this is line 4$
this is line 4
this is line 5$
this is line 5
sed -n 'l' data.txt
#输出 $代表换行符
this is line 1$
this is line 2$
this is line 3$
this is line 4$
this is line 5$
8)写入文件命令 w
格式 [address]w file
sed '1,2w 123.txt' data.txt 把data.txt文件的前两行写入123.txt文件
如果不想打印出内容可以加-n选项
123.txt
this is line 1
this is line 2
5)文件读取数据命令 r
讲一个独立文件中的数据插入到数据流中
格式 [address]r file 指定一个行号或者文本模式地址,会将文本中的数据插入到指定地址后
sed '3r 123.txt' data.txt
# 输出
this is line 1
this is line 2
this is line 3
this is line 1
this is line 2
this is line 4
this is line 5