I have two files tmp1.txt and tmp2.txt
tmp1.txt has
aaa.txt
bbb.txt
ccc.txt
ddd.txt
tmp2.txt has
/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
aaa.txt: test1
bbb.txt: test2
ccc.txt: test1
Thanks
Using 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
:
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 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:
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