使用 Bash 的两个列表之间的区别 [英] Difference between two lists using Bash

查看:25
本文介绍了使用 Bash 的两个列表之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我的 linux box 上有两个相关的文本文件列表:

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.

如何在 bash 中执行此操作?

How do I do this in bash?

推荐答案

使用 comm(1) 命令比较两个文件.它们都需要排序,如果它们很大,您可以事先进行排序,或者您可以使用 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 可以采用标志 -1-2-3 的组合来指示哪个文件抑制来自(文件 1 独有、文件 2 独有或两者共有)的行.

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).

仅获取旧文件中的行:

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

仅获取新文件中的行:

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

您可以将其输入到 while read 循环中以处理每一行:

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))

对于新行也类似.

这篇关于使用 Bash 的两个列表之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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