bash 使用 grep 删除文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3556341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:31:21  来源:igfitidea点击:

Removing text using grep

bash

提问by mrblippy

i am trying to remove a line that contains a particular pattern in a text file. i have the following code which does not work

我正在尝试删除文本文件中包含特定模式的行。我有以下代码不起作用

`grep -v "$varName" config.txt`

can anyone tell me how i can make it work properly, i want to make it work using grep and not sed

谁能告诉我如何使其正常工作,我想使用 grep 而不是 sed 使其工作

回答by Paul Tomblin

grep doesn't modify files. The best you can do if you insist on using grep and not sed is

grep 不修改文件。如果您坚持使用 grep 而不是 sed,您可以做的最好的事情是

grep -v "$varName" config.txt > $$ && mv $$ config.txt

Note that I'm using $$as the temporary file name because it's the pid of your bash script, and therefore probably not a file name going to be used by some other bash script. I'd encourage using $$in temp file names in bash, especially ones that might be run multiple times simultaneously.

请注意,我使用$$临时文件名是因为它是您的 bash 脚本的 pid,因此可能不是其他一些 bash 脚本将使用的文件名。我鼓励$$在 bash 中使用临时文件名,尤其是那些可能同时运行多次的文件名。

回答by ghostdog74

you can use sed, with in place -i

你可以使用 sed,就地 -i

sed -i '/pattern/d' file

回答by Spooks

try using -Ev

尝试使用 -Ev

grep -Ev 'item0|item1|item2|item3'

That will delete lines containing item[0-3]. let me know if this helps

这将删除包含 item[0-3] 的行。让我知道这是否有帮助