Как проверить, встречается ли один и тот же текст в двух разных файлах?

Как проверить, встречается ли один и тот же текст в двух разных файлах?

Я хочу проверить (трюк или какая-нибудь комбинация клавиш), существует ли текстовая строка в двух файлах.

Содержание файла один:

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

Содержание файла два:

c.txt
a.txt
d.txt

Как проверить, совпадает ли строка в файле 1 со строкой в ​​файле 2?

решение1

команда

Метод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, sortиgrep

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

Связанный контент