sed 流编辑器 是一款强大的 文本处理工具,工作中 sed 工具最常用到的有三个功能:
第一个,删除文本中特定的行:
例如,删除 demo.txt 文档中的 第3行
运行命令 sed ‘3d’ demo.txt
### 3 表示 第3行, d 代表 delete 删除,3d 就是 删除 文本中的第3行
sed '3d' demo.txt
例如,删除 demo.txt 文档中的 第 3 行 到 第 7 行
运行命令 sed ‘3,7d’ demo.txt
### 3,7 表示第3行到第7行,d 代表 delete 删除
sed '3,7d' demo.txt
例如,删除 demo.txt 文档中的第20 行后的 所有行
运行命令 sed ‘20,$d’ demo.txt
### $ 表示最后一行, 20,$ 就是 从第 20 行 到 最后 一行
sed '20,$d' demo.txt
下面介绍 一些 sed 的基本用法。
- 文本替换: sed ‘s#str1#str2#’ file.sed
单引号里面的第一个 s 是单词 substitute 的首字母,命令s表示替换,用 str1 替换文件 file.sed 里面的 str2,#是分隔符,用来分隔参数str1与str2,file.sed里面的内容如下:
I bought a red book and a yellow book. The two books totally cost 30$.
red book costs 10$, yellow book costs 20$.
I think yellow book is funny and red book is complex to understand.
Finally, I sent the yellow book to my brother,and left red book with me.
下面的命令默认将 file.sed 中每行的 第一个 “book” 替换为 “map”:
sed 's#book#map#' file.sed
下面的命令将 file.sed 中 每行的第二个 “book” 替换为 “map”,命令中最后的那个数字2表示 替换 第几个"book":
sed 's#book#map#2' file.sed
下面的命令会将 file.sed 中的 第3行 中的 "book"全部替换为 “map”,命令中的数字 ‘3’ 表示行号,第几行,命令末尾的 字母 ‘g’ 表示 global 全部,即 把 一 行中 所有的 “book” 字符全部替换为 “map”:
sed '3s#book#map#g' file.sed
结合正则表达式使用,用 /regepx/ 匹配目标行。下面的命令将 匹配到 /cost/ 行的所有 “book” 替换为 “map”:
sed '/cost/s#book#map#g' file.sed
- 文本删除: sed ‘[n]d’ file.sed
单引号中的字母 d 是 单词 delete 的首字母,命令 d 表示删除。[n] 表示被删除文本的行号范围,‘3d’ 表示删除 第3行,‘1,3d’ 表示删除 第1行到第3行,‘d’ 表示删除全部内容:
下面的命令将删除 file.sed 的 前 3行:
sed '1,3d' file.sed
结合正则表达式使用,用 /regepx/ 匹配行。下面的命令将删除 匹配到 ‘cost’ 字符的 行:
sed '/cost/d' file.sed
- 文本插入: sed ‘2i insert conent’ file.sed
单引号中的字母 i 是单词 insert 的首字母,命令 i 表示插入。2是行号,表示在第2行的位置插入(第一行下面插入一行),“insert content” 是被插入的内容:
sed '2i how are you' file.sed
结合正则表达式使用,用 /regepx/ 匹配行。下面的命令将在 匹配到 ‘cost’ 字符的 行上面新插入一行:
sed '/cost/i how are you' file.sed
- 文本拼接: sed ‘2a insert conent’ file.sed
单引号中的字母 a 是单词 append 的首字母,命令 a 表示拼接。2是行号,表示在第2行下面新插入一行,“insert content” 是新增行的内容:
sed '2a how are you' file.sed
结合正则表达式使用,用 /regepx/ 匹配行。下面的命令将在 匹配到 ‘cost’ 字符的 行下面新插入一行:
sed '/cost/a how are you' file.sed
综合应用,同时使用多个命令,命令之间使用 “;” 分隔。下面的命令将第2行中的所有 “book” 全部替换成 “map”, 并删除 第三行文本:
sed '2s#book#map#g;3d' file.sed