比较在bash两个文件(Compare two files in bash)

2019-10-20 23:37发布

我有两个文件tmp1.txt和tmp2.txt tmp1.txt有

aaa.txt
bbb.txt
ccc.txt
ddd.txt

tmp2.txt有

/tmp/test1/aaa.txt
/tmp/test1/aac.txt
/tmp/test2/bbb.txt
/tmp/test1/ccc.txt

我想,以检查是否存在tmp2.txt在tmp1.txt的文件,如果存在显示它,使其显示类似这样的东西哪一个

aaa.txt: test1
bbb.txt: test2
ccc.txt: test1

谢谢

Answer 1:

使用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


Answer 2:

我想使用标准工具来提出解决方案diffbasename

while read filename
do
    basename "$filename"
done < tmp2.txt > tmp2.basenames.txt
diff -u tmp1.txt tmp2.basenames.txt

这种解决方案的主要优点是它的简单性。 输出将看起来有些不同,虽然,在文件中区分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


Answer 3:

Bash的解决方案:

#!/bin/bash
while read file && a=$(grep -Fw "$file" tmp2.txt)
do
   echo "$(basename $a): $(dirname $a)"
done < tmp1.txt


Answer 4:

如果你不想用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


文章来源: Compare two files in bash