![如何從 shell 中顯示兩個檔案中的前 n 個不同行?](https://rvso.com/image/169416/%E5%A6%82%E4%BD%95%E5%BE%9E%20shell%20%E4%B8%AD%E9%A1%AF%E7%A4%BA%E5%85%A9%E5%80%8B%E6%AA%94%E6%A1%88%E4%B8%AD%E7%9A%84%E5%89%8D%20n%20%E5%80%8B%E4%B8%8D%E5%90%8C%E8%A1%8C%EF%BC%9F.png)
如何從 shell 中顯示兩個檔案中的前 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
假設您的檔案不包含製表符(如果包含,請選擇另一個明確的分隔符號),您可以這樣做
$ 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<&-