Bash - 在文件中查找关键字并删除其行 [英] Bash - find a keyword in a file and delete its line

查看:20
本文介绍了Bash - 在文件中查找关键字并删除其行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给出一个关键字,找到这个关键字aṕ在文件中出现的那一行,然后把整行擦掉.

I'd like to give a keyword, find the line where this keyword aṕpears in a file and erase the entire line.

这是我得到的,但它不能正常工作:

This is what I got but it is not working as it should:

KEYWORD='domain.com'
cat /etc/hosts | grep -v "$KEYWORD" > /etc/hosts

更新

这对我有用:

sed -i_bak -e '/domain.com/d'/etc/hosts

但是,由于我有两行带有domain.com"的行,有没有办法告诉 sed 只删除出现确切关键字domain.com"的行

However, as I had two lines with "domain.com", is there a way to tell sed to erase only the line where the exact keyword "domain.com" appears

这是/etc/hosts的原始内容:

This is the original content of /etc/hosts:

127.0.0.1       localhost       localhost.localdomain
222.111.22.222      hvn.domain.com
222.111.22.222      domain.com

这是命令 sed -i_bak -e '/domain.com/d'/etc/hosts 后的结果:

Here's how it end up after the command sed -i_bak -e '/domain.com/d' /etc/hosts:

127.0.0.1       localhost       localhost.localdomain

我试过 sed -i_bak -e '/<namourphoto.com.br>/d' ~/Desktop/hosts 但是没有用.

I tried sed -i_bak -e '/<namourphoto.com.br>/d' ~/Desktop/hosts but it didn't work.

结论

这是我想出的代码(基于优秀的人给我的帮助):

This is the code I came up with (based on the help the fine folks have given me):

D=domain.com
DOMAIN=`echo "$D" | sed 's/./\\./g'`
sed -i_bak -e "/[	]$DOMAIN/d" /etc/hosts

注意:

  • 我数着在要擦除的域之前总有一个标签

  • I am counting that there is always a tab before the domain to be erased

我正在自动转义域名的点.

I am automatically escaping the dots of the domain name.

推荐答案

使用流编辑器,sed:

sed -i ".bak" '/culpa/d' test.txt

以上将删除 test.txt 中包含 culpa 的行.它将创建原始文件(名为 test.txt.bak)的备份,并将就地修改原始文件.

The above will delete lines containing culpa in test.txt. It will create a backup of the original (named test.txt.bak) and will modify the original file in-place.

这篇关于Bash - 在文件中查找关键字并删除其行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆