How to extract duplicate rows

Hi! I have a file as below:

line1
line2
line2
line3
line3
line3
line4
line4
line4
line4

I would like to extract duplicate lines (not unique, triplicate or quadruplicate lines). Output will be as below:

line2
line2

I would appreciate if anyone can help. Thanks.

If your file is sorted then try below.

awk '{if(a!=$0){if(i==2){print a"\n"a}a=$0;i=0;i++}else{++i;a=$0}}' infile

thanks pravin27,
it works great.

$ ruby -ne 'BEGIN{h={}};(h[$_] ||= []) << $_;END{h.each{|k,v| puts v.join() if v.size==2}}' file
line2
line2

awk '{++a[$0];b[$0]=b[$0]?b[$0]"\n"$0:$0}END{ for (i in a) {if(a==2) print b}}' file
1 Like