bash 스크립트에서 두 파일 비교?

셸 스크립트에서 일치하는 데이터 두 개를 찾고 셸의 다른 파일에서 데이터 저장소를 복제하는 방법은 무엇입니까?

#!/bin/bash file1="/home/vekomy/santhosh/bigfiles.txt" file2="/home/vekomy/santhosh/bigfile2.txt" while read -r $file1; do while read -r $file2 ;do if [$file1==$file2] ; then echo "two files are same" else echo "two files content different" fi done done 

코드를 작성했지만 작동하지 않았습니다. 작성 방법

댓글

  • 사용해 보셨습니까? diff 명령?

답변

파일이 동일합니다. cmp -s를 사용합니다.

#!/bin/bash file1="/home/vekomy/santhosh/bigfiles.txt" file2="/home/vekomy/santhosh/bigfile2.txt" if cmp -s "$file1" "$file2"; then printf "The file "%s" is the same as "%s"\n" "$file1" "$file2" else printf "The file "%s" is different from "%s"\n" "$file1" "$file2" fi 

-s 플래그를 cmp로 설정하면 유틸리티가 “무음”으로 설정됩니다. 동일한 두 파일을 비교할 때 cmp의 종료 상태는 0이됩니다. 두 파일이 동일한 지 여부에 대한 메시지를 출력하기 위해 위 코드에서 사용됩니다.


두 입력 파일에 파일의 경로 이름 목록이 포함 된 경우 비교하고 싶다면 다음과 같이 이중 루프를 사용하십시오.

  

여기서 결과는 터미널과 file-comparison.out 파일 모두에서 생성됩니다.

두 입력 파일의 경로 이름에 새 줄이 포함되어 있지 않다고 가정합니다.

코드는 먼저 파일 중 하나에서 모든 경로 이름을 배열, files1, mapfile를 사용합니다. 다른 파일의 각 경로 이름에 대한 모든 경로 이름을 살펴야하므로 해당 파일을 두 번 이상 읽을 필요가 없도록이 작업을 수행합니다. 내부 루프의 $filelist1에서 읽는 대신 files1 배열의 이름을 반복합니다.

댓글

  • bash 셸에 전체 프로그램이 필요합니다.
  • @santhoshreddy 업데이트 된 답변보기

답변

가장 쉬운 방법은 diff 명령을 사용하는 것입니다.

예 :

첫 번째 파일이 file1.txt 및 그는 다음을 포함합니다.

I need to buy apples. I need to run the laundry. I need to wash the dog. I need to get the car detailed.` 

및 두 번째 파일 file2.txt

I need to buy apples. I need to do the laundry. I need to wash the car. I need to get the dog detailed. 

그런 다음 diff를 사용하여 다음 명령으로 두 파일간에 다른 줄을 자동으로 표시 할 수 있습니다.

diff file1.txt file2.txt

출력은 다음과 같습니다.

 2,4c2,4 < I need to run the laundry. < I need to wash the dog. < I need to get the car detailed. --- > I need to do the laundry > I need to wash the car. > I need to get the dog detailed. 

이 출력의 의미를 살펴 보겠습니다. 기억해야 할 중요한 점은 diff가 이러한 차이점을 설명 할 때 “규정적인 맥락에서 수행합니다.”는 첫 번째 파일을 두 번째 파일과 일치하도록 변경하는 방법을 알려준다는 것입니다. diff 출력의 첫 번째 줄에는 다음이 포함됩니다.

  • 첫 번째 파일에 해당하는 줄 번호
  • 문자 (추가는 a, 변경은 c, 삭제는 d )
  • 두 번째 파일에 해당하는 줄 번호

위 출력에서 “2,4c2,4 “는” 2 에서 4 는 행과 일치하도록 변경해야합니다. 2 ~ 4 (두 번째 파일). ” 그런 다음 각 파일에 해당 줄이 무엇인지 알려줍니다.

  • < 앞에 오는 줄은 첫 번째 파일의 줄입니다.
  • 앞에 오는 줄은 두 번째 파일의 줄입니다.
  • 세 개의 대시 ( “—“)는 파일 1과 파일 2의 줄을 구분합니다.

출처

답변

순수한 파일 비교를위한 bash 셸 스크립트 :

#!/usr/bin/env bash # @(#) s1 Demonstrate rudimentary diff using shell only. # Infrastructure details, environment, debug commands for forum posts. # Uncomment export command to run as external user: not context, pass-fail. # export PATH="/usr/local/bin:/usr/bin:/bin" set +o nounset LC_ALL=C ; LANG=C ; export LC_ALL LANG pe() { for _i;do printf "%s" "$_i";done; printf "\n"; } pl() { pe;pe "-----" ;pe "$*"; } db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; } db() { : ; } C=$HOME/bin/context && [ -f "$C" ] && $C set -o nounset FILE1=${1-data1} shift FILE2=${1-data2} # Display samples of data files. pl " Data files:" head "$FILE1" "$FILE2" # Set file descriptors. exec 3<"$FILE1" exec 4<"$FILE2" # Code based on: # http://www.linuxjournal.com/content/reading-multiple-files-bash # Section 2, solution. pl " Results:" eof1=0 eof2=0 count1=0 count2=0 while [[ $eof1 -eq 0 || $eof2 -eq 0 ]] do if read a <&3; then let count1++ # printf "%s, line %d: %s\n" $FILE1 $count1 "$a" else eof1=1 fi if read b <&4; then let count2++ # printf "%s, line %d: %s\n" $FILE2 $count2 "$b" else eof2=1 fi if [ "$a" != "$b" ] then echo " File $FILE1 and $FILE2 differ at lines $count1, $count2:" pe "$a" pe "$b" # exit 1 fi done exit 0 

생성 :

$ ./s1 Environment: LC_ALL = C, LANG = C (Versions displayed with local utility "version") OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64 Distribution : Debian 8.9 (jessie) bash GNU bash 4.3.30 ----- Data files: ==> data1 <== I need to buy apples. I need to run the laundry. I need to wash the dog. I need to get the car detailed. ==> data2 <== I need to buy apples. I need to do the laundry. I need to wash the car. I need to get the dog detailed. ----- Results: File data1 and data2 differ at lines 2, 2: I need to run the laundry. I need to do the laundry. File data1 and data2 differ at lines 3, 3: I need to wash the dog. I need to wash the car. File data1 and data2 differ at lines 4, 4: I need to get the car detailed. I need to get the dog detailed. 

특정 명령을 제거하여 첫 번째 차이에서 종료 할 수 있으며 읽은 모든 행을 보려면

의 페이지를 참조하십시오. iv id “& 3″과 같은 파일 설명자에 대한 자세한 내용은 = “4221551235”>

를 참조하세요.

축하합니다. drl

댓글

  • head는 외부 유틸리티이며 $HOME/bin/context? 그리고 상단에서 주석은 무엇을 의미합니까?
  • 헤드는 입력을 표시합니다. 차이는 없습니다. 다른 항목과 마찬가지로 " context "는 환경 컨텍스트를 표시하기 위해 로컬입니다. 이를 포함하면 ' OS 버전과 유틸리티 버전이 다른지 여부를 논의 할 필요가 없습니다.
  • 알아 주셔서 감사합니다.
  • 내보내기가 누락되었습니다.
  • 아직도 ' 댓글을 이해하지 못합니다.' " 외부 사용자 "는 무엇이며, 순수한 스크립트의 경로 bash?
  • 우리는 상점에 대한 코드를 작성하므로 경로 설정이 외부 사용자에 따라 다를 수 있습니다. 설정을 생략해야하는 경우 추가합니다. 코드가 실행 된 환경에 대한 정보를 표시하도록 수정 된 템플릿입니다. 예를 들어 클라이언트의 경우 데모 코드 대신 프로덕션 코드로 변환되는 경우 ' 로컬 경로가 사용되지 않도록해야합니다. for context는 해당 파일이 발견되지 않으면 아무 일도 일어나지 않고 오류도 발생하지 않고 버전이 나열되지 않도록 설계되었습니다.

답글 남기기

이메일 주소를 발행하지 않을 것입니다. 필수 항목은 *(으)로 표시합니다