With awk
$ awk -F: 'NF==1 && $0 ~ s{print p ORS $0} {s=$NF; p=$0}' ip.txt
@1:N:0:ABC
ABC
-F:
use :
as delimiter, makes it easy to get last column
s=$NF; p=$0
save last column value and entire line for printing later
NF==1
if line doesn't contain :
$0 ~ s
if line contains the last column data saved previously
- if search data can contain regex meta characters, use
index($0,s)
instead to search literally
- note that this code assumes input file having line containing
:
followed by line which doesn't have :
With GNU sed
(might work with other versions too, syntax might differ though)
$ sed -nE '/:/{N; /.*:(.*)\n.*\1/p}' ip.txt
@1:N:0:ABC
ABC
/:/
if line contains :
N
add next line to pattern space
/.*:(.*)\n.*\1/
capture string after last :
and check if it is present in next line
again, this assumes input like shown in question.. this won't work for cases like
@1:N:0:ABC
@1:N:0:XYZ
XYZ