Skip to content

Instantly share code, notes, and snippets.

@cGuille
Last active August 3, 2017 11:07
Show Gist options
  • Save cGuille/09764a31ce786c8af4227dd56eb46af5 to your computer and use it in GitHub Desktop.
Save cGuille/09764a31ce786c8af4227dd56eb46af5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Installation:
# - Download this file.
# - Name it `missinglines`.
# - Make it executable (`chmod +x missinglines`).
# - Move it to your PATH.
set -o errexit
print_usage() {
echo "${1}missinglines <file1> <file2>" >&2
echo "${1}Print lines from file1 which are not in file2." >&2
}
if [[ $* == *'--help'* ]]; then
print_usage
exit
fi
if [[ $# != 2 ]]; then
echo "Expected two arguments:" >&2
print_usage ' '
exit 64
fi
file1="$1"
file2="$2"
if [[ ! -f $file1 ]]; then
echo "Cannot read '$file1'." >&2
print_usage ' '
exit 64
fi
if [[ ! -f $file2 ]]; then
echo "Cannot read '$file2'." >&2
print_usage ' '
exit 64
fi
file1_is_copied=nope
file2_is_copied=nope
file1_is_sorted=yep
sort -C "$file1" || file1_is_sorted=nope
file2_is_sorted=yep
sort -C "$file2" || file2_is_sorted=nope
sort_to_tempfile() {
local tmpfile="$(mktemp missinglines_XXXXXXXXXX)"
cat "$1" | sort > "$tmpfile"
echo "$tmpfile"
}
if [[ $file1_is_sorted == nope ]]; then
file1="$(sort_to_tempfile "$file1")"
file1_is_copied=yep
fi
if [[ $file2_is_sorted == nope ]]; then
file2="$(sort_to_tempfile "$file2")"
file2_is_copied=yep
fi
comm -23 "$file1" "$file2"
if [[ $file1_is_copied == yep ]]; then
rm "$file1"
fi
if [[ $file2_is_copied == yep ]]; then
rm "$file2"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment