2017-10-03 10 views
1

파일의 행을 인쇄하려면 cat, tail, head 또는 grep 등을 사용할 수 있습니다. 그러나 제 문제는 다소 복잡합니다. . 나는 그것을 이해할 수 없었다.세 번째 파일에 저장된 행 번호에 따라 두 파일의 행을 인쇄하는 방법

두 파일이 있는데 세 번째 파일에 행 번호가 있으면이 두 파일의 행을 나란히 인쇄하려고합니다.

파일 A를 :

예를 들어 다음과 같이의 나의 처음 두 파일을 가정 해 봅시다

FileA first sentence 
FileA second sentence 
FileA third sentence 

파일 B :

FileB BBfirst sentence 
FileB BBsecond sentence 
FileB BBthird sentence 

다음과 같이 파일 C가 될 수 있습니다 :

파일 C :

3 
    1 

그래서 저는 다음과 같이 인쇄 할 :

FileA third sentence  FileB BBthird sentence 
    FileA first sentence FileB BBfirst sentence 

내가 어떻게 할 수 있습니까? 구조에

답변

1

AWK :

솔루션 1 : 나는 그 배열을 통해 마지막으로 이송에서, 배열로 FILEA와 fileb 저장 값에서 다음 가장 높은 File_C의 자리의 값을 복용하고 있습니다.

awk 'FNR==NR{a[$0];len=len>$0?len:$0;next} (FNR in a){array[FNR]=array[FNR]?array[FNR] OFS $0:$0} END{for(j=1;j<=len;j++){if(array[j]){print array[j]}}}' fileC fileA fileB 

솔루션 중 하나가 아닌 라이너 형태를 추가 중입니다.

awk ' 
FNR==NR{ 
    a[$0]; 
    len=len>$0?len:$0; 
    next 
} 
(FNR in a){ 
    array[FNR]=array[FNR]?array[FNR] OFS $0:$0 
} 
END{ 
    for(j=1;j<=len;j++){ 
    if(array[j]){ 
     print array[j] 
} 
} 
} 
' fileC fileA fileB 

출력은 다음과 같습니다.

FileA first sentence FileB BBfirst sentence 
FileA third sentence FileB BBthird sentence 

해결 방법 2 : 여기 단순히 배열에 자신의 발생에 따라 요소를 저장하고 첫 번째 라인이되도록 FILEA와 fileb 위해 오는 때마다 변수의 값을 재설정, FILEC에서 어떤 최대 숫자의 개념을 사용하고 있지 않다 우리 for 루프의 일부 사이클을 절약 할 수 있습니다 (우리는 내 솔루션 1에서 그럴 수 없었습니다).

awk ' 
FNR==NR{ 
a[$0]; 
next 
} 
FNR==1{ 
i="" 
} 
(FNR in a){ 
++i; 
array[i]=array[i]?array[i] OFS $0:$0 
} 
END{ 
for(j=1;j<=i;j++){ 
    if(array[j]){ 
    print array[j] 
} 
} 
} 
' file_c file_a file_b 

출력은 다음과 같습니다.

FileA first sentence FileB BBfirst sentence 
FileA third sentence FileB BBthird sentence