采取几个文件的行交叉

时间:2014-01-15 17:49:21

标签: bash

我看到comm可以执行2个文件,diff3可以执行3个文件。我想做更多的文件(5)。

一种方式:

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

此过程可以转换为脚本

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*

这看起来像编写得很糟糕的代码,即使像我这样的新手,还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

这比它必须要复杂得多。这是另一种方法。

#!/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"