[英]Compare two files in bash
I have two files tmp1.txt and tmp2.txt tmp1.txt has 我有两个文件tmp1.txt和tmp2.txt,tmp1.txt有
aaa.txt
bbb.txt
ccc.txt
ddd.txt
tmp2.txt has tmp2.txt具有
/tmp/test1/aaa.txt
/tmp/test1/aac.txt
/tmp/test2/bbb.txt
/tmp/test1/ccc.txt
I want to check if the files in tmp1.txt exists in tmp2.txt and if it exists display which one it has so it displays something similar to this 我想检查tmp1.txt中的文件是否存在于tmp2.txt中,如果存在,则显示它具有哪个文件,因此显示与此类似的内容
aaa.txt: test1
bbb.txt: test2
ccc.txt: test1
Thanks 谢谢
Using awk
: 使用
awk
:
awk -F/ 'FNR==NR {a[$1];next} $NF in a {print $NF ": " $(NF-1)}' tmp1.txt tmp2.txt
aaa.txt: test1
bbb.txt: test2
ccc.txt: test1
I would like to propose a solution using the standard tools diff
and basename
: 我想使用标准工具
diff
和basename
提出一个解决方案:
while read filename
do
basename "$filename"
done < tmp2.txt > tmp2.basenames.txt
diff -u tmp1.txt tmp2.basenames.txt
The main advantage of this solution is its simplicity. 该解决方案的主要优点是简单。 The output will look a little different though, differentiating between files in
tmp1.txt
( -
), tmp2.txt
( +
), or both ( 不过,输出看起来会有些不同,区别
tmp1.txt
( -
), tmp2.txt
( +
)或两者( ):
):
--- tmp1.txt 2014-09-17 17:09:43.000000000 +0200
+++ tmp2.basenames.txt 2014-09-17 17:13:12.000000000 +0200
@@ -1,4 +1,4 @@
aaa.txt
+aac.txt
bbb.txt
ccc.txt
-ddd.txt
Bash Solution: 重击解决方案:
#!/bin/bash
while read file && a=$(grep -Fw "$file" tmp2.txt)
do
echo "$(basename $a): $(dirname $a)"
done < tmp1.txt
If you don't want to use awk, there's a little bash cycle: 如果您不想使用awk,则有一些bash循环:
while read f; do
isFound="$(grep /$f tmp2.txt 2>/dev/null)"
if [ ! -z "$isFound" ]; then
theDir=$(echo "$isFound"|cut -d'/' -f3)
echo "$f: $theDir"
fi
done <tmp1.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.