파일 이름은 같지만 내용이 다른 파일을 찾는 방법

파일 이름은 같지만 내용이 다른 파일을 찾는 방법

이름은 같지만 내용이 다른 두 개의 디렉터리에서 텍스트 파일을 찾으려고 합니다.

아래는 내 코드이지만 여기에서 계속 충돌이 발생합니다.

cati=`ls $1 | cat $i`

catj=`ls $2 | cat $j` 

등...

어떻게 수정할 수 있나요?

#!/bin/bash

if [ $# -ne 2 ];then
    echo "Usage ./search.sh dir1 dir2"
    exit 1
elif [ ! -d  $1 ];then
    echo "Error cannot find dir1"
    exit 2
elif [ ! -d  $2 ];then
        echo "Error cannot find dir2"
        exit 2
elif [ $1 == $2 ];then
    echo "Error both are same directories"

else
    listing1=`ls $1`
    listing2=`ls $2`
    for i in $listing1; do
            for j in $listing2; do
                if [ $i == $j ];then
                     cati=`ls $1 | cat $i`
                     catj=`ls $2 | cat $j`
                     if [ $cati != $catj ];then
                           echo $j
                     fi
                fi

            done
    done
fi

답변1

find다음은 및를 사용하는 또 다른 옵션 입니다 .while read loop

#!/usr/bin/env bash

##: Set a trap to clean up temp files.
trap 'rm -rf "$tmpdir"' EXIT

##: Create temp directory using mktemp.
tmpdir=$(mktemp -d) || exit

##: If arguments less than 2
if (( $# < 2 )); then
  printf >&2 "Usage %s dir1 dir2 \n" "${BASH_SOURCE##*/}"
  exit 1
fi

dirA=$1
dirB=$2

##: Loop through the directories
for d in "$dirA" "$dirB"; do
  if  [[ ! -e $d ]]; then  ##: If directory does not exists
    printf >&2 "%s No such file or directory!\n" "$d"
    exit 1
  elif [[ ! -d $d ]]; then  ##: If it is not a directory.
    printf >&2 "%s is not a directory!\n" "$d"
    exit 1
  fi
done

##: If dir1 and dir2 has the same name.
if [[ $dirA = $dirB ]]; then
  printf >&2 "Dir %s and %s are the same directory!\n" "$dirA" "$dirB"
  exit 1
fi

##: Save the list of files in a file using find.
find "$dirA" -type f -print0 > "$tmpdir/$dirA.txt"
find "$dirB" -type f -print0 > "$tmpdir/$dirB.txt"


##: Although awk is best for comparing 2 files I'll leave that to the awk masters.

while IFS= read -ru "$fd" -d '' file1; do  ##: Loop through files of dirB
  while IFS= read -r -d '' file2; do ##: Loop through files of dirA
    if [[ ${file1##*/} = ${file2##*/} ]]; then  ##: If they have the same name
      if ! cmp -s "$file1" "$file2"; then ##: If content are not the same.
        printf 'file %s and %s has the same name but different content\n' "$file1" "$file2"
      else
        printf 'file %s and %s has the same name and same content\n' "$file1" "$file2"
      fi
    fi
  done < "$tmpdir/$dirA.txt"
done {fd}< "$tmpdir/$dirB.txt"

답변2

"신규 사용자"를 환영합니다! 내 생각에 여기서 가장 큰 문제는 전체 파일을 쉘 변수에 로드하려고 하는 것입니다. 첫째, 이것은 확장이 잘 되지 않습니다. 둘째, 파일을 셸로 읽을 때 백틱으로 인한 변경으로 인해 비교가 제대로 작동하지 않습니다. 마지막으로 파일의 모든 공백으로 인해 코드가 손상됩니다. 하지만 이 모든 것에 대한 해결책이 있습니다! :)

반환 값을 사용하면 diff파일을 셸로 완전히 읽지 않아도 됩니다. 이와 같이:

if diff $i $j; then
     echo $j
fi

기타 제안사항:

  • 셸에서 조건문을 실행하려면 over 를 사용하는 것이 [[좋습니다 . 어수선한 항목과 더 잘 [작동합니다 [[.
  • 분실물에는 어떤 것이 있나요? $i또는 비어 있으면 $j어떻게 되나요? 그러면 쉘은 해당 행에서 오류를 발생시킵니다. "$i"쉘을 실행하거나 강제 실행하여 누락된 변수에 대한 위치를 예약 할 수 있습니다 "$j".
  • 주택 검사귀하의 코드를 읽고 모범 사례를 제안해 드립니다.
  • Google의 셸 스타일 가이드다른 많은 기술이 있습니다.

관련 정보