使用Bash的两个列表之间的区别 [英] Difference between two lists using Bash
问题描述
好吧,我在Linux框中的文本文件中有两个相关列表:
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).
要仅在旧文件中获取行:
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)
您可以将其输入到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屋!