bash 如何从文件中删除包含特定字符串的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24595025/
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-18 10:48:29  来源:igfitidea点击:

How to remove line containing a specific string from file?

stringbashsed

提问by Jared Aaron Loo

I have a file BookDB.txt which stores information in the following manner :

我有一个 BookDB.txt 文件,它以以下方式存储信息:

C++ for dummies:Jared:10.67:4:5
Java for dummies:David:10.45:3:6 
PHP for dummies:Sarah:10.47:2:7

Assuming that during runtime, the scipt asks the user for the title he wants to delete. This is then stored in the TITLE variable. How do I then delete the line containing the string in question? I've tried the following command but to no avail :

假设在运行时,scipt 询问用户他想要删除的标题。然后将其存储在 TITLE 变量中。然后如何删除包含相关字符串的行?我尝试了以下命令但无济于事:

sed '/$TITLE/' BookDB.txt >> /dev/null

回答by fedorqui 'SO stop harming'

You can for example do:

例如,您可以执行以下操作:

$ title="C++ for dummies"
$ sed -i "/$title/d" a
$ cat a
**Java for dummies**:David:10.45:3:6
**PHP for dummies**:Sarah:10.47:2:7

Note few things:

注意几点:

  • Double quotes in sed are needed to have you variable expanded. Otherwise, it will look for the fixed string "$title".
  • With -iyou make in-place replacement, so that your file gets updated once sed has performed.
  • dis the way to indicate sedthat you want to delete such matching line.
  • 需要在 sed 中使用双引号来扩展变量。否则,它将查找固定字符串“$title”。
  • 随着-i您进行就地替换,一旦 sed 执行,您的文件就会更新。
  • d是指示sed您要删除此类匹配行的方式。

回答by Avinash Raj

Your command should be,

你的命令应该是,

sed "/$TITLE/d" file

To save the changes, you need to add -iinline edit parameter.

要保存更改,您需要添加-i内联编辑参数。

sed -i "/$TITLE/d" file

For variable expansion in sed, you need to put the code inside double quotes.

对于 sed 中的变量扩展,您需要将代码放在双引号内。