countunique
countunique

Reputation: 4296

Taking line intersection of several files

I see comm can do 2 files and diff3 can do 3 files. I want to do for more files (5ish).

One way:

comm -12 file1 file2 >tmp1
comm -12 tmp1 file3 >tmp2
comm -12 tmp2 file4 >tmp3
comm -12 tmp3 file5

This process could be turned into a script

comm -12 $1 $2 > tmp1
for i in $(seq 3 1 $# 2>/dev/null); do
  comm -12 tmp`expr $i - 2` $(eval echo '$'$i) >tmp`expr $i - 1`
done
if [ $# -eq 2 ]; then
  cat tmp1
else
  cat tmp`expr $i - 1`
fi
rm tmp*

This seems like poorly written code, even to a newbie like me, is there a better way?

Upvotes: 0

Views: 63

Answers (1)

that other guy
that other guy

Reputation: 123650

It's quite a bit more convoluted than it has to be. Here's another way of doing it.

#!/bin/bash
# Create some temp files to avoid trashing and deleting tmp* in the directory
tmp=$(mktemp)
result=$(mktemp)

# The intersection of one file is itself
cp "$1" "$result"
shift

# For each additional file, intersect with the intermediate result
for file
do
    comm -12 "$file" "$result"  > "$tmp" &&  mv "$tmp" "$result"
done

cat "$result" && rm "$result"

Upvotes: 2

Related Questions