Valentin Montmirail Valentin Montmirail - 1 month ago 15
Bash Question

Intersection of N files

I've got a little problem in

bash
.

I've got
N
files containing filenames, and I would like to find the list of filenames which are contained in all the file (the intersection of the files).

When there is 2 files, I found this solution:
sort file1 file2 | uniq -d
, and this is actually doing what I want.

But how to generalize it to
N
files in the same folder ?




File1

1
2
3
4

File2

1
4

File3

2
3
4

Output expected:

4


Thanks in advance,
Best Regards.

Answer

I`m not Marc B, but still, here`s the implementation of his idea:

intersect() {
    sort "$@" | uniq -cd | grep "^[^0-9]*$# "
}

# usage example
intersect file1 file2 file3

[EDIT:] To overcome the problem of duplicate lines within the same file, I`d do something like this:

intersect() {
    for file in "$@"; do
        sort -u "$file"
    done | sort | uniq -cd | grep "^[^0-9]*$# "
}