Shell 删除文件中包含特定字符的句子

Shell 删除文件中包含特定字符的句子,利用正则表达式删除包含某个单词的句子不是件难事。本章给出了一个解决类似问题的方法。sed是进行文本替换的不二之选。我们可以使用sed将匹配的句子替换成空白。

Shell删除文件中包含特定字符的句子

实战演练

先创建一个包含替换文本的文件。例如:

$ cat sentence.txt
Linux refers to the family of Unix-like computer operating systems
that use the Linux kernel. Linux can be installed on a wide variety
of computer hardware, ranging from mobile phones, tablet computers
and video game consoles, to mainframes and supercomputers. Linux is
predominantly known for its use in servers.
Bash

我们的目标是删除包含mobile phones的句子。可以用下面的sed语句来实现:

$ sed 's/ [^.]*mobile phones[^.]*\.//g' sentence.txt
Linux refers to the family of Unix-like computer operating systems
that use the Linux kernel. Linux is predominantly known for its use
in servers.
Bash

 这里假设文件中没有出现跨行的句子。也就是说,句子总是完整地出现在同一行中。

工作原理

sed的正则表达式s/ [^.]*mobile phones[^.]*\.//g采用的格式为s/substitution_pattern/replacement_string/g。它将与substitution_pattern相匹配的每一处内容都用replacement_string替换掉。

本例中的substitution_pattern是用来匹配整句文本的正则表达式。文件中的每一句话都是以空格开头,以.结尾。正则表达式要匹配内容的格式就是:空格+若干文本+需要匹配的字符串+若干文本+句点。一个句子中除了作为分隔符的句点之外,可以包含任意字符。因此需要使用[^.],该模式可以匹配除句点之外的任意字符。*表示之前的字符可以出现任意多次。用来匹配文本的mobile phones被放置在两个 [^.]* 之间。每一个匹配的句子均被//替换(注意,//之间没有任何内容)。

学习本章内容可以参考如何使用正则表达式sed 命令 相关知识。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Shell 实例

登录

注册