How does this perl one-liner display lines that 2 files have in common?
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
Use comm -12 file1 file2 to get common lines in both files. You may also needs your file to be sorted to comm to work as expected. Or using grep command you need to add -x option to match the whole line as a matching pattern. The F option is telling grep that match pattern as a string not a regex match.
The -n
command line option transforms the code to something equivalent to
while ($ARGV = shift @ARGV) { open ARGV, $ARGV; LINE: while (defined($_ = <ARGV>)) { $seen{$_} .= @ARGV; print $_ if $seen{$_} =~ /10$/; } }
While the first file is being read, scalar @ARGV
is 1
. For each line, 1
will be appended to the %seen
entry.
While the second file is being read, scalar @ARGV
is 0
. So if a line was in file 1 and in file2, the entry will look like 1110000
(it was 3× in file1, 4× in file2).
We only want to output common lines exactly one time. We do this when a common line was first seen in file2, so $seen{$_}
is 1110
. This is expressed as the regex /10$/
: The string 10
must appear at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With