如何对比source.txt与old.txt并移除两文件共有的行?
移除source.txt中与old.txt重复的行
问题描述:
现有两个文件source.txt和old.txt,需要对比这两个文件,将同时存在于old.txt和source.txt中的行从source.txt中移除。source.txt 内容:
abc.com def.com ghi.com 123.com 456.com 789.com 700.com 710.comold.txt 内容:
123.com 700.com def.com期望更新后的 source.txt:
abc.com ghi.com 456.com 789.com 710.com
给你几个实用的命令行解决方法:
方法1:用grep快速过滤
这是最常用的方式,直接反向匹配过滤重复行:
grep -vxFf old.txt source.txt > temp.txt && mv temp.txt source.txt
参数解释:
-v:只输出不匹配的行-x:强制整行匹配,避免类似123.com.cn这种部分匹配的误删-F:把old.txt里的内容当固定字符串,不是正则表达式-f old.txt:从old.txt里读取要排除的内容
先把结果写到临时文件,再覆盖原source.txt,防止直接重定向清空原文件。
方法2:用comm对比已排序文件
如果文件内容可以排序,用comm工具更直观:
sort source.txt > sorted_source.txt sort old.txt > sorted_old.txt comm -23 sorted_source.txt sorted_old.txt > temp.txt && mv temp.txt source.txt rm sorted_source.txt sorted_old.txt
参数解释:
-23:只保留仅在source.txt里有的行,隐藏另外两列(仅old.txt的行、共同存在的行)
方法3:用awk灵活处理
awk适合更复杂的文本处理场景,这里逻辑清晰:
awk 'NR==FNR{arr[$0];next}!($0 in arr)' old.txt source.txt > temp.txt && mv temp.txt source.txt
逻辑说明:
- 先读old.txt,把每行内容存进数组
arr - 再读source.txt,只输出不在
arr里的行
内容的提问来源于stack exchange,提问作者Janet D
相关产品推荐
相关产品推荐

