我需要多次删除包含某个字符串的文件中的所有行,例如,如果我的文件是这样的:
This is a test toRemove first line
This is a test toRemove second line toRemove
应该生成一个只有第一行的文件This is a test toRemove first line
我正在尝试从命令行在 linux 上执行此操作,并尝试像这样使用 grep 或 sedgrep -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/