![シェルから 2 つのファイルの最初の n 行を表示するにはどうすればよいでしょうか?](https://rvso.com/image/169416/%E3%82%B7%E3%82%A7%E3%83%AB%E3%81%8B%E3%82%89%202%20%E3%81%A4%E3%81%AE%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E6%9C%80%E5%88%9D%E3%81%AE%20n%20%E8%A1%8C%E3%82%92%E8%A1%A8%E7%A4%BA%E3%81%99%E3%82%8B%E3%81%AB%E3%81%AF%E3%81%A9%E3%81%86%E3%81%99%E3%82%8C%E3%81%B0%E3%82%88%E3%81%84%E3%81%A7%E3%81%97%E3%82%87%E3%81%86%E3%81%8B%3F.png)
シェルから 2 つのファイルの最初の 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<&-