sed 命令使用入门

上一篇说了 awk 命令的基本使用方法,这一篇就来说说其兄弟 sed 的使用方法吧(传说之中,Linux 命令行下处理文件文件三大上古神器:grep、awk、sed,每一个都很好很强大,有时间了说说 grep 的实现以及使用)!
sed 主要是按照既定规则修改每行的特定内容为指定内容,可以称它为“流编辑器”。准备实验所需文件 songs.txt,其内容如下:

1, Justin Timberlake, Title 545, Price $6.30
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
4, Lady Gaga, Title 118, Price $6.30
5, Johnny Cash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $6.30
7, John Lennon, Title 271, Price $7.90

替换

将文件每行的 7.30 替换为 6.30:
sed 's/6.30/7.30/' songs.txt > songs2.txt
输出文件 songs2.txt 内容如下:

1, Justin Timberlake, Title 545, Price $7.30
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
4, Lady Gaga, Title 118, Price $7.30
5, Johnny Cash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $7.30
7, John Lennon, Title 271, Price $7.90

过滤

sed 命令也常常用作行内容过滤器。例如,我们要过滤选出包含“John”的每行:
sed -n '/John/p' songs.txt > johns.txt
输出文件 johns.txt 内容如下:

5, Johnny Trash, Title 482, Price $6.50
7, John Lennon, Title 271, Price $7.90

参考

https://www.lifewire.com/example-uses-of-sed-2201058
http://man.linuxde.net/sed

原文地址:https://www.cnblogs.com/optor/p/8232968.html