Let me tell you how it works: It constructs a string for every distinct line in a file, appending the number of files still to process to the string (it doesn't really matter what character is appended, only important is that it is different for every file)
I.e. whenever line "xyz" occurs in the first file, it appends a '1' to the string for this line, because there is still one file to process (in case of two files). When "xyz" occurs in the second file, it always appends '0', because there is no file in the queue still to process
Whenever, after appending a character, the string for line "xyz" has the contents "...01", i.e. a '1' at the end of the string, and before that at least one '0', then it prints the line. Which happens exactly once, when the line "xyz" is found the first time in the second file. Before that there was no '1' in the string. After that there will be multiple '1's at the end of the string
This is an ingenious oneliner. But when you have more than two files to compare, this script will search through all the files, but still only print the common lines in the last two files. To generalize it to more files, you would have to search if all numbers occur in the string and it wouldn't work for more than 10 files.
perl -ne '$seen{$_}= " " x (@ARGV+1) if (not exists $seen{$_}); substr +($seen{$_},@ARGV,1)="1"; if (@ARGV==0 and $seen{$_}=~ /^1+$/) { print +; $seen{$_}.="x"}' FILES ...
This oneliner works with any amount of files. It doesn't append but changes a ' ' to a '1' at the position in the string corresponding to the file. It also has to initialize the string the first time. And has to invalidate the string (by appending an 'x') after printing it so that lines occuring twice in the last file don't get printed twice. The lines get printed when the last file is processed and the string is all '1's
PS: Doing things in the shell will almost always be slower than in perl
In reply to Re: find common lines in many files
by jethro
in thread find common lines in many files
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |