줄 수가 다른 두 개의 서로 다른 파일을 병합합니다.

줄 수가 다른 두 개의 서로 다른 파일을 병합합니다.

두 개의 거대한 파일이 있는데 두 파일의 줄 수가 동일하지 않습니다.

파일 1

61346877
41724134
85406965
59647779
25199749
86213
45417131
41905714
19415458
1828594
56543876
70603415

파일 2

212
1231
324234
213

원하는 출력

61346877,212
41724134,1231
85406965,324234
59647779,213
25199749,212
86213,1231
45417131,324234
41905714,213
19415458,212
1828594,1231
56543876,324234
70603415,213

답변1

큰 타격:

size1=$( wc -l < file1 )
size2=$( wc -l < file2 )
i=0
while (( i < size1 )); do
    cat file2
    (( i += size2 ))
done | paste -d, file1 -  | head -n $size1

headfile1의 크기가 file2의 짝수 배수가 아닌 경우 입력을 파이프합니다 .

산출

61346877,212
41724134,1231
85406965,324234
59647779,213
25199749,212
86213,1231
45417131,324234
41905714,213
19415458,212
1828594,1231
56543876,324234
70603415,213

3줄짜리 awk 프로그램

awk -v OFS=, '
    # read the smaller file into memory
    NR == FNR {size2++; file2[FNR] = $0; next} 

    # store the last line of the array as the zero-th element
    FNR == 1 && NR > 1 {file2[0] = file2[size2]} 

    # print the current line of file1 and the corresponding file2 line
    {print $0, file2[FNR % size2]}
' file2 file1

답변2

file2의 모든 행을 읽고 나면 file2의 중복 내용이 남게 됩니다. 다음은 file2의 줄 수를 변수로 취하고 파일의 총 줄 수를 확인할 때마다 재설정되는 카운터를 기반으로 file2의 줄을 인쇄하는 awk/ 솔루션 입니다.sed

$ awk -v file2lines=$(wc -l file2 | cut -f1 -d' ') 'BEGIN{count=1} {if(count > file2lines) count=1; printf $1",";system("sed -n -e "count"p file2");count++}' file1

61346877,212
41724134,1231
85406965,324234
59647779,213
25199749,212
86213,1231
45417131,324234
41905714,213
19415458,212
1828594,1231
56543876,324234
70603415,213

답변3

사용이 간편함awk ;)

awk 'FNR==NR{a[i++]=$0; max=i; next} {if ((NR % max) == 0) {i=max-1} else {i=(NR%max) - 1}; printf "%s,%s\n",$0,a[i]}' file2 file1

출력 예

61346877,212
41724134,1231
85406965,324234
59647779,213
25199749,212
86213,1231
45417131,324234
41905714,213
19415458,212
1828594,1231
56543876,324234
70603415,213

관련 정보