赞
踩
目录
sed是Linux的一种文本编辑器,与grep、awk并称为Linux文本三剑客
基本用法:
sed 选项 '操作' 文件1 文件2 ....
-n,--quiet,--silent: 取消自动打印模式空间
-e 脚本, --expression=脚本: 添加“脚本”到程序的运行列表
-f 脚本文件, --file=脚本文件: 添加“脚本文件”到程序的运行列表
--follow-symlinks: 直接修改文件时跟随软链接
-i[SUFFIX], --in-place[=SUFFIX]: edit files in place (makes backup if SUFFIX supplied)
-l N, --line-length=N: 指定“l”命令的换行期望长度
--posix: 关闭所有 GNU 扩展
-E, -r, --regexp-extended: use extended regular expressions in the script(for portability use POSIX -E).
-s, --separate: consider files as separate rather than as a single,continuous long stream.
--sandbox: operate in sandbox mode.
-u, --unbuffered: 从输入文件读取最少的数据,更频繁的刷新输出
-z, --null-data: 使用 NUL 字符分隔各行
a:增加,在当前行下面增加一行指定内容
c:替换,将选定行替换为指定内容
d:删除,删除选定的行。
i:插入,在选定行上面插入一行指定内容
p:打印,如果同时指定行,表示打印指定行;如果不指定行,则表示打印出所有内容;如果有非打印字符,则以ASCII码输出。其通常与"-n"选项一起使用。
s:替换,替换指定字符
首先创建一个文档
vim 123.txt
内容为:
This is a tes
sed
123456
654321
000000
888888
lhf@ubuntu:~/source$ sed ' ' 123.txt
This is a tes
sed
123456
654321
000000
888888
再使用p操作时要带上参数,否则会出现重复打印现象
lhf@ubuntu:~/source$ sed 'p' 123.txt | lhf@ubuntu:~/source$ sed -n 'p' 123.txt |
还可以显示指定行数
lhf@ubuntu:~/source$ sed -n '2p' 123.txt //显示第2行内容
sed
lhf@ubuntu:~/source$ sed -n '3p' 123.txt //显示第3行内容
123456lhf@ubuntu:~/source$ sed -n '2,3p' 123.txt //显示2~3行内容
sed
123456lhf@ubuntu:~/source$ sed -n '$p' 123.txt //显示最后一行内容
888888
sed '指定行 s/需要替换的字符串/替换后的字符串/替换标记
替换标记:
(1)g:表示要替换所有匹配的行
(2)w:将替换后的结果保存到文档
(3)n:替换匹配行的第n个匹配字符
lhf@ubuntu:~/source$ sed 's/1/one/g' 123.txt This is a tes //将文本中所有的1全部替 sed //换成one one23456 65432one 000000 888888 | lhf@ubuntu:~/source$ sed '4s/1/one/g' 123.txt |
lhf@ubuntu:~/source$ sed 's/^/*/g' 123.txt *This is a tes *sed //在每一行的开头加上* *123456 *654321 *000000 *888888 | lhf@ubuntu:~/source$ sed 's/$/end/g' 123.txt This is a tesend sedend 123456end //在每一行的末尾加上end 654321end 000000end 888888end |
lhf@ubuntu:~/source$ sed 's/8/*/3' 123.txt This is a tes sed //将每行第三个匹配的字符替换为* 123456 654321 000000 88*888 | lhf@ubuntu:~/source$ sed '/is/s/e/a/g' 123.txt This is a tas sed //将包含is的行中的e替换为a 123456 654321 000000 888888 |
值得注意的是以上操作只是改变了输出流(只改变了显示的内容),并没有改变文本中的内容,如要改变文本的内容需要加上-i参数。
lhf@ubuntu:~/source$ sed '2d' 123.txt | lhf@ubuntu:~/source$ sed '2,3d' 123.txt This is a tas 654321 //删除2~3行 000000 888888 |
lhf@ubuntu:~/source$ sed '/1/d' 123.txt This is a tas sed //删除包含1的行 000000 888888 |
注意这里的删除只改变了输出流,并未改变文本中的内容,需要加上-i参数才能改变文本内容。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。