如何删除 bash 中的部分重复项?

如何删除 bash 中的部分重复项?

如何使用 awk、grep 或 sort 删除 bash 中的部分重复项?
我试过了,sort -u FILE | uniq -w20但不太可靠。

输入:

http://www.website.com/1.file
http://www.website.com/2.file
http://www.website.com/3.file
http://www.someotherwebsite.com/1.file
http://www.someotherwebsite.com/2.file
http://www.someotherwebsite.com/3.file

预期输出:

http://www.website.com/3.file
http://www.someotherwebsite.com/3.file

答案1

如果所有公共字符串都格式正确,则一个解决方案是使用awk前三个字段作为键,例如:

awk -F/ '{a[$1$2$3]=$0} END {for(k in a) {print a[k]}}'

这会将每行拆分为基于/分隔符的字段。我们使用前 3 个字段作为数组中的键,并将整行存储为值。

完成输入后,我们将遍历数组并打印值,该值始终是与给定键匹配的最后一行。

正如所建议的,我们可以通过剥离最后一部分并比较其余部分来使其更加灵活:

awk -F/ '{orig=$0; $NF=""; a[$0]=orig} END {for(k in a) {print a[k]}}'

这将保存整行不作修改,使最后一个字段为空字符串,然后执行与之前相同的其余数组工作。

相关内容