如何檢查相同的文字是否出現在兩個不同的文件中

如何檢查相同的文字是否出現在兩個不同的文件中

我想檢查(技巧或任何快捷方式)文字字串是否存在於兩個文件中。

文件一的內容是

a.txt
b.txt
c.txt
d.txt

文件二的內容是

c.txt
a.txt
d.txt

如何檢查檔案一中的字串是否與檔案二中的字串相符?

答案1

命令

方法一:

for i in `cat p1`; do grep -i "$i" p2 >/dev/null; if [[ $? == 0 ]]; then echo "$i exsists in both files"; else echo "$i doesnt exsists in file p2"; fi; done

輸出

a.txt exsists in both files
b.txt doesnt exsists in file p2
c.txt exsists in both files
d.txt exsists in both files

答案2

join,sortgrep

join <(sort /path/to/source) <(sort /path/to/destination) | grep '<string to check>

測試

cat source
a.txt
b.txt
c.txt
d.txt

cat destination
c.txt
a.txt
d.txt

join <(sort source) <(sort destination) | grep 'a.txt'
a.txt

join <(sort source) <(sort destination) | grep 'b.txt'

如果需要檢查兩個文件的內容是否不匹配,可以發出以下命令

cmp --silent <(sort source) <(sort destination) || echo "files are different"

測試

cmp --silent <(sort source) <(sort destination) || echo "files are different"
files are different

將來源檔案中未包含在目標檔案中的所有行新增至 /var/tmp/unmatched 檔案中

comm -23 <(sort source) <(sort destination) > /var/tmp/unmatched

從來源檔案中刪除目標檔案中不包含的所有行

comm -1 <(sort source) <(sort destination) >| source

由於我們使用的是 bash,並且如果您已將 noclobber 設定為set -o noclobber,那麼您應該使用語法>|

答案3

使用下面的 awk 指令完成

f2count=`awk 'END{print NR}' p2`
f1count=`awk 'END{print NR}' p1 `
comm_p1_p2=`awk 'NR==FNR{a[$0];next}($0 in a){print $0}' p1 p2| awk 'END{print NR}'`

if [[ $f1count -eq $f2count ]] && [[ $f1count -eq $comm_p1_p2 ]]; then echo "both files p1  and p2 content are same"; else echo "different content found on file p1  and p2"; fi

相關內容