巴什 - 差两个列表 [英] Bash - Difference Between two lists

查看:81
本文介绍了巴什 - 差两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我有我的Linux系统中两个相关的列表中的文本文件:

 的/ tmp / oldList
 的/ tmp / newList

我需要比较这些列表,看看有什么得到了添加的直线和删除得到什么线路。
然后,我需要循环这些线路,并依据他们是否添加或移除对他们的行动。我该怎么做这在bash?


解决方案

使用 COMM(1)命令来比较两个文件。他们都需要进行排序,您可以事先做,如果他们是大的,或者你可以使用bash内嵌做的进程替换

通讯可采取标志 1 -2 -3 表明哪些文件从(唯一到文件1,独特的文件2或双方共同)。

要获得行仅在旧文件:

  COMM -23≤(排序的/ tmp / oldList)≤(排序的/ tmp / newList)

要获得行仅在新文件中:

  COMM -13≤(排序的/ tmp / oldList)≤(排序的/ tmp / newList)

您可以养活成而读循环来处理每行:

 同时读取旧;做
    ...做的东西与旧$
完成< ≤(COMM -23≤(排序的/ tmp / oldList)≤(排序的/ tmp / newList))

和类似的新线。

Ok, I have two related lists on my linux box in text files:

 /tmp/oldList
 /tmp/newList

I need to compare these lists to see what lines got added and what lines got removed. I then need to loop over these lines and perform actions on them based on whether they were added or removed. How do I do this in bash?

解决方案

Use the comm(1) command to compare the two files. They both need to be sorted, which you can do beforehand if they are large, or you can do it inline with bash process substitution.

comm can take a combination of the flags -1, -2 and -3 indicating which file to suppress lines from (unique to file 1, unique to file 2 or common to both).

To get the lines only in the old file:

comm -23 <(sort /tmp/oldList) <(sort /tmp/newList)

To get the lines only in the new file:

comm -13 <(sort /tmp/oldList) <(sort /tmp/newList)

You can feed that into a while read loop to process each line:

while read old ; do
    ...do stuff with $old
done < <(comm -23 <(sort /tmp/oldList) <(sort /tmp/newList))

and similarly for the new lines.

这篇关于巴什 - 差两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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