grep 查找文件中的一行,然后删除该行

grep for a line in a file then remove the line

$ cat example.txt

产量:

example
test
example

我想从此文件中删除 'test' 字符串。

$ grep -v test example.txt > example.txt 
$ cat example.txt 
$

下面的方法可行,但我感觉还有更好的方法!

$ grep -v test example.txt > example.txt.tmp;mv example.txt.tmp example.txt 
$ cat example.txt 
example
example

值得注意的是,这将在一个超过 10,000 行的文件中。

干杯

你可以使用 sed,

sed -i '/test/d' example.txt

-i 保存对该文件所做的更改。所以你不需要使用重定向运算符。

-i[SUFFIX], --in-place[=SUFFIX]
             edit files in place (makes backup if SUFFIX supplied)

你的做法是正确的,但在 mv 之前使用 && 以确保 grep 成功,否则你将删除原始文件:

grep -F -v test example.txt > example.txt.tmp && mv example.txt.tmp example.txt

我还添加了 -F 选项,因为您说过要删除字符串,而不是正则表达式。

您可以使用 sed -i 但是您需要担心如何转义 sed 定界符 and/or 并且 sed 不支持搜索字符串因此您需要尝试转义所有可能的组合搜索字符串中的正则表达式字符以尝试使 sed 将它们视为文字字符(由于正则表达式字符的位置敏感性质,您无法自动执行该过程)并且它可以节省您的是手动命名您的 tmp 文件,因为 sed 使用无论如何内部一个。

哦,另一种选择 - 您可以将 GNU awk 4.* 与 "inplace editing" 一起使用。它也像 sed 一样在内部使用 tmp 文件,但它确实支持字符串操作,因此您无需尝试转义 RE 元字符,并且它没有分隔符作为语法的一部分需要担心:

awk -i inplace -v rmv="test" '!index([=11=],rmv)' example.txt

任何 grep/sed/awk 解决方案都会 运行 眨眼间处理 10,000 行文件。