![¿Cómo puedo mostrar las primeras n líneas diferentes en dos archivos desde un Shell?](https://rvso.com/image/169416/%C2%BFC%C3%B3mo%20puedo%20mostrar%20las%20primeras%20n%20l%C3%ADneas%20diferentes%20en%20dos%20archivos%20desde%20un%20Shell%3F.png)
¿Cómo puedo mostrar las primeras n líneas diferentes en dos archivos desde un shell? Lo he intentado grep -vf
pero realmente no funciona.
Supongamos n = 5 Esta entrada:
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
Produciría la salida:
This line is not the same
This is still not the same
Neither is this
Nor this
DIFFERENT
Respuesta1
Esta es mi propuesta:
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
Respuesta2
Suponiendo que sus archivos no contienen el carácter TAB (si lo contienen, elija otro delimitador inequívoco), podría hacerlo
$ 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
Respuesta3
Usar primitivas de bash, usar descriptores de archivos fijos para simplificar las cosas. (No probado)
# 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<&-