Last active
March 6, 2019 03:58
-
-
Save kou1okada/c16cd3fd6544f987aacb38285377cac3 to your computer and use it in GitHub Desktop.
sorted_diff.sh - Show differences for sorted inputs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# sorted_diff.sh - Show differences for sorted inputs. | |
# Copyright (c) 2019 Koichi OKADA. All right reserved. | |
# This script distributed under the MIT license. | |
# | |
# Note: | |
# This script is wastefull. | |
# Use the `join` command included in the coreutils. | |
# `sorted_diff diff` is same to `join -v1 -v2`, | |
# `sorted_diff left` is same to `join -v1`, | |
# `sorted_diff right` is same to `join -v2`, | |
# and | |
# `sorted_diff same` is same to `join`. | |
function sorted_diff () # <mode> <lfile> <rfile> | |
# Show differences for sorted inputs. | |
# | |
# Args: | |
# <mode> : one of {diff|left|right|same} | |
# <lfile>, <rfile> : files to check differences | |
{ | |
(( $# != 3 )) && { echo -e "\e[31;1mError: \e[0m Wrong noumber of arguments."; return 1; } | |
[[ ! "${1:0:1}" =~ [dlrs] ]] && { echo -e "\e[31;1mError: \e[0m unknown mode: $1"; return 1; } | |
awk -v m="${1:0:1}" ' | |
BEGIN { | |
while(getline < ARGV[1]) l[nl++] = $0; | |
while(getline < ARGV[2]) r[nr++] = $0; | |
for (il = ir = 0; il < nl && ir < nr;) { | |
if (l[il] == r[ir]) {if (m == "s" ) print l[il]; il++; ir++;} | |
else if (l[il] < r[ir]) {if (m == "d" || m == "l") print l[il]; il++;} | |
else if (l[il] > r[ir]) {if (m == "d" || m == "r") print r[ir]; ir++;} | |
} | |
for (;il < nl; il++) if (m == "d" || m == "l") print l[il]; | |
for (;ir < nr; ir++) if (m == "d" || m == "r") print r[ir]; | |
} | |
' "$2" "$3" | |
} | |
[ "$(readlink -f -- "$0")" = "$(readlink -f -- "$BASH_SOURCE")" ] && { | |
(( $# == 3 )) && sorted_diff "$@" || echo "Usage: ${0##*/} <mode={diff|left|right|same}> <lfile> <rfile>" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment