development

리눅스 터미널에서 두 파일 비교

big-blog 2020. 6. 8. 08:00
반응형

리눅스 터미널에서 두 파일 비교


"a.txt""b.txt" 라는 두 파일에는 모두 단어 목록이 있습니다. 이제 "a.txt"에 추가되어 있고 "b.txt"에 없는 단어를 확인하고 싶습니다 .

두 사전을 비교할 때 효율적인 알고리즘이 필요합니다.


vim을 설치 한 경우 다음을 시도하십시오.

vimdiff file1 file2

또는

vim -d file1 file2

환상적입니다.여기에 이미지 설명을 입력하십시오


그들을 정렬하고 사용하십시오 comm:

comm -23 <(sort a.txt) <(sort b.txt)

comm(정렬 된) 입력 파일을 비교하고 기본적으로 a에 고유 한 행, b에 고유 한 행 및 둘 다에 존재하는 세 개의 열을 출력합니다. 지정하여 -1, -2및 / 또는 -3당신은 해당 출력을 억제 할 수 있습니다. 따라서 comm -23 a ba에 고유 한 항목 만 나열합니다. <(...)구문을 사용하여 파일을 즉석에서 정렬합니다. 이미 정렬되어 있으면 필요하지 않습니다.


시도 sdiff( man sdiff)

sdiff -s file1 file2

diff리눅스에서 도구를 사용 하여 두 파일을 비교할 수 있습니다. 당신은 사용할 수 있습니다 --changed 그룹 포맷을 하고 --unchanged 그룹 형식의 필터에 필요한 데이터에 대한 옵션을.

다음 세 가지 옵션을 사용하여 각 옵션에 대한 관련 그룹을 선택할 수 있습니다.

  • '% <'은 (는) FILE1에서 줄을 가져옵니다.

  • '%>'는 FILE2에서 줄을 가져옵니다.

  • 두 파일에서 줄을 제거하기위한 ''(빈 문자열)

예 : diff --changed-group-format = "% <"--unchanged-group-format = ""file1.txt file2.txt

[root@vmoracle11 tmp]# cat file1.txt 
test one
test two
test three
test four
test eight
[root@vmoracle11 tmp]# cat file2.txt 
test one
test three
test nine
[root@vmoracle11 tmp]# diff --changed-group-format='%<' --unchanged-group-format='' file1.txt file2.txt 
test two
test four
test eight

에서 diff 출력 스타일을 선호하는 경우 git 저장소에없는 파일을 비교하기 git diff위해 --no-index플래그 와 함께 사용할 수 있습니다 .

git diff --no-index a.txt b.txt

각각 약 200k 개의 파일 이름 문자열을 가진 두 개의 파일을 사용하여 (내장 time명령을 사용하여)이 접근법을 다른 답변과 비교했습니다.

git diff --no-index a.txt b.txt
# ~1.2s

comm -23 <(sort a.txt) <(sort b.txt)
# ~0.2s

diff a.txt b.txt
# ~2.6s

sdiff a.txt b.txt
# ~2.7s

vimdiff a.txt b.txt
# ~3.2s

comm반면, 훨씬 빠른 것 같다 git diff --no-index나타납니다이 사랑하는 스타일의 출력을위한 가장 빠른 방법이 될 수 있습니다.


2018-03-25 업데이트--no-index git 저장소 안에 있고 해당 저장소 내에서 추적되지 않은 파일을 비교하지 않는 한 실제로 플래그를 생략 할 수 있습니다 . 에서 맨 페이지 :

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.


You can also use: colordiff: Displays the output of diff with colors.

About vimdiff: It allows you to compare files via SSH, for example :

vimdiff /var/log/secure scp://192.168.1.25/var/log/secure

Extracted from: http://www.sysadmit.com/2016/05/linux-diferencias-entre-dos-archivos.html


Also, do not forget about mcdiff - Internal diff viewer of GNU Midnight Commander.

For example:

mcdiff file1 file2

Enjoy!


Use comm -13 (requires sorted files):

$ cat file1
one
two
three

$ cat file2
one
two
three
four

$ comm -13 <(sort file1) <(sort file2)
four

Here is my solution for this :

mkdir temp
mkdir results
cp /usr/share/dict/american-english ~/temp/american-english-dictionary
cp /usr/share/dict/british-english ~/temp/british-english-dictionary
cat ~/temp/american-english-dictionary | wc -l > ~/results/count-american-english-dictionary
cat ~/temp/british-english-dictionary | wc -l > ~/results/count-british-english-dictionary
grep -Fxf ~/temp/american-english-dictionary ~/temp/british-english-dictionary > ~/results/common-english
grep -Fxvf ~/results/common-english ~/temp/american-english-dictionary > ~/results/unique-american-english
grep -Fxvf ~/results/common-english ~/temp/british-english-dictionary > ~/results/unique-british-english

그것을 위해 awk를 사용합니다. 테스트 파일 :

$ cat a.txt
one
two
three
four
four
$ cat b.txt
three
two
one

awk :

$ awk '
NR==FNR {                    # process b.txt  or the first file
    seen[$0]                 # hash words to hash seen
    next                     # next word in b.txt
}                            # process a.txt  or all files after the first
!($0 in seen)' b.txt a.txt   # if word is not hashed to seen, output it

복제물이 출력됩니다.

four
four

중복을 피하려면 a.txt에서 새로 만난 각 단어를 seen해시에 추가하십시오.

$ awk '
NR==FNR {
    seen[$0]
    next
}
!($0 in seen) {              # if word is not hashed to seen
    seen[$0]                 # hash unseen a.txt words to seen to avoid duplicates 
    print                    # and output it
}' b.txt a.txt

산출:

four

단어 목록이 쉼표로 구분되어 있으면 다음과 같습니다.

$ cat a.txt
four,four,three,three,two,one
five,six
$ cat b.txt
one,two,three

여분의 랩 ( for루프)을 몇 번해야합니다 .

awk -F, '                    # comma-separated input
NR==FNR {
    for(i=1;i<=NF;i++)       # loop all comma-separated fields
        seen[$i]
    next
}
{
    for(i=1;i<=NF;i++)
        if(!($i in seen)) {
             seen[$i]        # this time we buffer output (below):
             buffer=buffer (buffer==""?"":",") $i
        }
    if(buffer!="") {         # output unempty buffers after each record in a.txt
        print buffer
        buffer=""
    }
}' b.txt a.txt

이번에 출력 :

four
five,six

참고 URL : https://stackoverflow.com/questions/14500787/comparing-two-files-in-linux-terminal

반응형