删除文件中重复的行

本文介绍如何使用Linux命令行工具去除/etc/hosts文件中的重复条目,并保持必要的网络配置信息不变。通过使用sort和uniq命令组合,可以轻松地解决hosts文件中出现的重复问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在经过多次执行脚本后时候突然发现:/etc/hosts下面有好多重复的行,突然想起来之前记得学过有命令的,但是忘了,后来在群里面吼了几句,有好多牛人相应,闲来与大家分享,O(∩_∩)O~

[root@zy zy]# cat /etc/hosts
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1 localhost.localdomain localhost puppet
192.168.55.229 master.puppet.com master
192.168.55.230 node1.puppet.com node1
192.168.55.231 node2.puppet.com node2
192.168.55.81 puppetmaster.99bill.com
192.168.55.229 zy.99bill.com zy
192.168.55.229 zy.99bill.com zy
192.168.55.229 zy.99bill.com zy

# cat /etc/hosts | sort | uniq

[root@zy zy]# cat /etc/hosts | sort | uniq
127.0.0.1 localhost.localdomain localhost puppet
192.168.55.229 master.puppet.com master
192.168.55.229 zy.99bill.com zy
192.168.55.230 node1.puppet.com node1
192.168.55.231 node2.puppet.com node2
192.168.55.81 puppetmaster.99bill.com
# Do not remove the following line, or various programs
# that require network functionality will fail.

注意查看:顺序发生了变化,这是因为sort的原因。

那么我们可以直接执行:

# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1 localhost.localdomain localhost puppet
192.168.55.229 master.puppet.com master
192.168.55.230 node1.puppet.com node1
192.168.55.231 node2.puppet.com node2
192.168.55.81 puppetmaster.99bill.com
192.168.55.229 zy.99bill.com zy

注意:这次我们发现只是重复的行给删除了,只保留了一行。

另外:

# cat /etc/hosts | sort -u

可以直接删除重复的,嘿嘿。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值