Skip to content

Instantly share code, notes, and snippets.

@zed
Created January 11, 2013 18:33
Show Gist options
  • Select an option

  • Save zed/4512881 to your computer and use it in GitHub Desktop.

Select an option

Save zed/4512881 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Print common lines between all given files
#
# exit on any error
set -e
# exit if no files given
USAGE="Usage: $0 file1 [file2 [file3...]]"
if [ "$#" == "0" ]; then
echo "$USAGE"
exit 2
fi
# create temporary directory
tmpdir=$(mktemp -d) || exit 1
# remove temporary directory on exit
trap "rm -rf -- '$tmpdir'" EXIT
# initial copy
result="$tmpdir/result"
cp <(sort -u "$1") "$result"
shift
# while there are files left
while (( "$#" )); do
# extract common lines two files at a time
comm -12 "$result" <(sort -u "$1") >"$tmpdir/tmp"
mv "$tmpdir/tmp" "$result"
shift
done
# output result
cat "$result"
# cleanup
rm -rf -- "$tmpdir"
trap - EXIT
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment