쉘에서 두 파일의 처음 n개의 다른 줄을 어떻게 표시할 수 있습니까?

쉘에서 두 파일의 처음 n개의 다른 줄을 어떻게 표시할 수 있습니까?

쉘에서 두 파일의 처음 n개의 다른 줄을 어떻게 표시할 수 있습니까? 나는 시도했지만 grep -vf실제로 작동하지 않습니다.

n = 5라고 가정합니다. 이 입력은 다음과 같습니다.

file1

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o

file2

This line is not the same
b
c
d
This is still not the same
Neither is this
g
h
Nor this
DIFFERENT
k
This is not the same, too
m
another different line
o

출력을 생성합니다.

This line is not the same
This is still not the same
Neither is this
Nor this
DIFFERENT

답변1

이것이 내 제안입니다:

diff -u file1 file2 --unchanged-line-format= --old-line-format= --new-line-format=%L | head -n 5

This line is not the same
This is still not the same
Neither is this
Nor this
DIFFERENT

답변2

파일에 TAB 문자가 포함되어 있지 않다고 가정하면(있는 경우 다른 명확한 구분 기호 선택) 수행할 수 있습니다.

$ paste file1 file2 | awk -F'\t' '$2 != $1 {print $2; n++} n==5 {exit}'
This line is not the same
This is still not the same
Neither is this
Nor this
DIFFERENT

답변3

bash 기본 요소를 사용하고 고정된 파일 설명자를 사용하여 작업을 단순하게 유지합니다. (테스트되지 않음)

# open the two files on fd8 and fd9, should have some error checking
exec 8<file1 9<file2
# start the loop
for(c=0;c<6;)
do
    # read a line from first file, don't worry about EOF 
    IFS="" read -r -u 8 l1
    # read a line from second file, exit the loop if EOF
    read -r -u 9 l2 || break
    # loop if the 2 lines are the same
    [ "$l1" -eq "$l2" ] && continue
    # ok, a different line. Output from file2, bump count and loop
    let c++
    printf '%s\n' "$l2"
done
# If we get here we either have hit EOF on file2 or have printed our 6 lines
# Either way just tidy up
# close the file descriptiors
exec 8<&- 9<&-

관련 정보