regex - 从文件中删除多次包含字符串的行

标签 regex sed command-line grep

我需要多次删除包含某个字符串的文件中的所有行,例如,如果我的文件是这样的:

This is a test toRemove first line

This is a test toRemove second line toRemove
应该生成一个只有第一行的文件
This is a test toRemove first line
我正在尝试从命令行在 linux 上执行此操作,并尝试像这样使用 grep 或 sed
grep -d "toRemove.*toRemove" myFile > myOtherFile

sed '/\toRemove.*toRemove/!d' myFile > myOtherFile
但似乎没有任何效果。有人知道如何获得这个吗?

最佳答案

您可以使用

sed '/toRemove.*toRemove/d' myFile > myOtherFile
grep -v "toRemove.*toRemove" myFile > myOtherFile
sed : 注意\t匹配一个 TAB 字符,和 !d删除与模式不匹配的行。因此,您需要删除 \之前 t并删除 !之前d .grep : 你应该用过 -v反转正则表达式检查结果的选项(它将输出与模式不匹配的所有行)。
online demo :
s='This is a test toRemove first line
This is a test toRemove second line toRemove'
sed '/toRemove.*toRemove/d' <<< "$s"
# => This is a test toRemove first line
grep -v 'toRemove.*toRemove' <<< "$s"
# => This is a test toRemove first line

关于regex - 从文件中删除多次包含字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67620131/

相关文章:

用于表单验证的正则表达式 1-9999

jquery - 文本匹配不适用于阿拉伯语问题可能是由于阿拉伯语的正则表达式

regex - 如何使用 sed 命令删除一行中除前三个字符以外的所有字符?

java - 在 Java 项目中使用 jar?

command-line - 如何使用AWS CLI创建Dynamodb全局二级索引?

java - 使用正则表达式获取 HTML 标签内的信息

python - 具有非捕获字符的 python re.sub() 出现意外结果

regex - 匹配特定模式后在数字之间插入空格

bash - 使用 sed 将日期格式从 DD/MM/YYYY 更改为 YYYY-MM-DD

linux - Linux下如何判断自己是否在无线接口(interface)上