![두 개의 다른 파일에 동일한 텍스트가 나타나는지 어떻게 확인할 수 있습니까?](https://rvso.com/image/169430/%EB%91%90%20%EA%B0%9C%EC%9D%98%20%EB%8B%A4%EB%A5%B8%20%ED%8C%8C%EC%9D%BC%EC%97%90%20%EB%8F%99%EC%9D%BC%ED%95%9C%20%ED%85%8D%EC%8A%A4%ED%8A%B8%EA%B0%80%20%EB%82%98%ED%83%80%EB%82%98%EB%8A%94%EC%A7%80%20%EC%96%B4%EB%96%BB%EA%B2%8C%20%ED%99%95%EC%9D%B8%ED%95%A0%20%EC%88%98%20%EC%9E%88%EC%8A%B5%EB%8B%88%EA%B9%8C%3F.png)
두 파일에 텍스트 문자열이 있는지 확인하고 싶습니다(트릭 또는 단축키).
파일 1의 내용은 다음과 같습니다.
a.txt
b.txt
c.txt
d.txt
파일 2의 내용은 다음과 같습니다.
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