bash 在文件中搜索字符串并通过 Shell 脚本将其从该文件中删除

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

Search a string in a file and delete it from this file by Shell Script

bashshell

提问by virtue

I want to delete a line containing a specific string from the file. How can I do this without using awk? I tried to use sedbut I could not achieve it.

我想从文件中删除包含特定字符串的行。我如何在不使用的情况下做到这一点awk?我尝试使用sed但我无法实现。

回答by mvds

This should do it:

这应该这样做:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

它将在所有文件 ( *)中将所有出现的“deletethis”替换为“”(无),并就地编辑它们。

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

在第二种形式中,模式可以更安全地编辑,它可以备份任何修改过的文件,后缀为“.backup”。

The third form is the way some versions of sedlike it. (e.g. Mac OS X)

第三种形式是有些版本sed喜欢它的方式。(例如 Mac OS X)

man sedfor more information.

man sed想要查询更多的信息。

回答by user unknown

sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

使用 'd' 删除一行。这至少适用于 GNU-Sed。

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

如果您的 Sed 没有选项,就地更改文件,也许您可​​以使用中间文件来存储修改:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source usually doesn't work: sed '/pattern/d' file > fileso make a copy before trying out, if you doubt it.

直接写入源代码通常是行不通的:sed '/pattern/d' file > file因此,如果您对此表示怀疑,请在尝试之前制作一份副本。

回答by kenorb

Try the vim-way:

尝试 vim 方式:

ex -s +"g/foo/d" -cwq file.txt