값 1이 정확히 일치하면 2개 파일의 값 2와 일치합니다.

값 1이 정확히 일치하면 2개 파일의 값 2와 일치합니다.

목록이 포함된 파일이 2개 있습니다. 열 1은 사용자 ID이고 열 2는 관련 값입니다.

# cat file1
e3001 75
n5244 30
w1453 500

#cat file2
d1128 30
w1453 515
n5244 30
e3001 55

고려해야 할 사항.

  1. 두 파일의 userId가 정확하게 정렬되지 않았을 수 있습니다.
  2. 파일의 userId 수는 다를 수 있습니다.

필수의

  • 먼저, file1:column1의 userId는 file2:column1의 UserId와 일치해야 합니다.
  • 다음으로 file1:column2의 값을 file2:column2의 값과 비교합니다.
  • 값에 차이가 있는 곳을 인쇄합니다. 및 추가 userId(있는 경우)

산출:

e3001 has differnece, file1 value: 75 & file2 value: 55
w1453 has differnece, file1 value: 500 & file2 value: 515
d1128 is only present in filename: file1|file2

1liner-awk 또는 bash 루프 솔루션에 오신 것을 환영합니다.

루프를 시도하고 있지만 쓰레기가 뱉어지고 있습니다. 논리 오류가 있는 것 같습니다.

#!/usr/bin/env bash

## VARIABLES
FILE1=file1
FILE2=file2
USERID1=(`awk -F'\t' '{ print $1 }' ${FILE1}`)
USERID2=(`awk -F'\t' '{ print $1 }' ${FILE2}`)
USERDON1=(`awk -F'\t' '{ print $2 }' ${FILE1}`)
USERDON2=(`awk -F'\t' '{ print $2 }' ${FILE2}`)

for user in ${USERID1[@]}
do
    for (( i = 0; i < "${#USERID2[@]}"; i++ ))
    #for user in ${USERID2[@]}
    do
        if [[ ${USERID1[$user]} == ${USERID2[i]} ]]
        then
            echo ${USERID1[$user]} MATCHES BALANCE FROM ${FILE1}: ${USERDON1[$i]} WITH BALANCE FROM ${FILE2}: ${USERDON2[$i]}
        else
            echo ${USERID1[$user]} 
        fi
    done
done

다음은 Linux 상자에서 직접 복사한 파일입니다. 탭으로 구분되어 있지만 내가 아는 한 awk는 탭도 사용할 수 있습니다.

#cat file1
e3001   55
n5244   30
w1453   515

답변1

글쎄요, 말하자면 당신의 대본은 경치 좋은 길을 택합니다. 간단한 방법은 어떻습니까 awk? 좋다

awk '
NR==FNR         {ARR[$1] = $2
                 F1      = FILENAME
                 next
                }
($1 in ARR)     {if ($2 != ARR[$1]) print $1 " has difference," \
                                          F1 " value: " ARR[$1] \
                                          " & " FILENAME " value: " $2 
                 delete ARR[$1]
                 next
                }
                {print $1 " is only present in filename: " FILENAME
                }
END             {for (a in ARR) print a " is only present in filename: " F1
                }
' file[12]
d1128 is only present in filename: file2
w1453 has difference, file1 value: 500 & file2 value: 515
e3001 has difference, file1 value: 75 & file2 value: 55

file1의 모든 내용을 배열로 읽은 다음 file2의 각 줄에 대해 $1배열 인덱스를 확인하고 차이가 있으면 인쇄하고(없으면 존재하지 않음) delete배열 요소를 저장합니다( delete아마도 일부 awk에 구현이 누락되었습니다. btw). 존재하지 않는 경우 그에 따라 인쇄하십시오. 이 END섹션에서는 나머지 배열 요소가 모두 file1에만 존재하므로 인쇄됩니다.

답변2

주석은 자명합니다.

awk '
    BEGIN {file1 = ARGV[1]; file2 = ARGV[2]}

    # Load all file1 contents
    NR == FNR {map[$1] = $2; next}
    
    # If $1 is not in m then this key is unique to file2
    !($1 in map) {uniq[$1]; next}

    # If $1 is in m and the value differs there are delta
    # between the two files. Save it.
    $1 in map && map[$1] != $2 {diff[$1] = $2; next}

    # The two files have all the same data.
    {delete map[$1]}

    END {
        # Anything is in diff are in both files but
        # with different values
        for ( i in diff )
            print i, "has difference,", file1, "value:", map[i], "&", file2, "value:", diff[i]

        # Anything is still in m is only in file 1
        for ( i in map )
            if (!(i in diff))
                print i, "is only present in filename :", file1

        # Anything is in uniq is unique to file2
        for ( i in uniq )
            print i, "is only present in filename :", file2
    }
' file1 file2

답변3

쉘은 이런 종류의 작업에 끔찍한 도구입니다.또한 일반적으로 쉘 스크립트에서는 쉘 변수에 대문자를 사용하지 않아야 합니다. 전역 환경 셸 변수는 관례상 모두 대문자이므로 이름 지정 충돌이 발생하고 디버깅하기 어려운 문제가 발생할 수 있습니다. 마지막으로 스크립트는 파일을 4번(!) 읽어야 하며그 다음에데이터 처리.

그런데 또 다른 이상한 접근 방식이 있습니다(솔직히 말해서루딕스더 좋지만 이미 이 글을 썼기 때문에 어쨌든 게시하겠습니다):

$ awk '{
  if(NR==FNR) {
    fn1=FILENAME;
    f1[$1]=$2;
    next
  }
  f2[$1]=$2;
  if($1 in f1){
    if($2 != f1[$1]){
      printf "%s is different; %s value: %s & %s value: %s\n", \
             $1,fn1,$2,FILENAME,f1[$1]
    }
  }
  else{
    print $1,"is only present in filename:", FILENAME
  }
}
END{
  for(id in f1){
    if( !(id in f2) ){print id,"is only present in afilename:",fn1}
  }
}' file1 file2
d1128 is only present in filename: file2
w1453 is different; file1 value: 515 & file2 value: 500
e3001 is different; file1 value: 55 & file2 value: 75

답변4

awk 'function printUniq(Id, fName){
         printf("%s is only present in filename: %s\n", Id, fName)
}

{ fileName[nxtinput+0]=FILENAME }
!nxtinput{ Ids[$1]=$2; next }

($1 in Ids){ if($2!=Ids[$1])
                 printf ("%s has difference, %s value: %s & %s value: %s\n",\
                 $1, fileName[0], Ids[$1], fileName[1], $2);
             delete Ids[$1];
             next
}
{ printUniq($1, fileName[1]) }
END{ for(id in Ids) printUniq(id, fileName[0]) }' file1 nxtinput=1 file2

관련 정보