-
-
Save forestbaker/723f00105ff7852b0dd6 to your computer and use it in GitHub Desktop.
Bash function that compares files containing key-value pairs.
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
#$1,2 = files containing x=y style key-values | |
#sort, awk, grep friendly | |
#Duplicate keys are not handled | |
function kvdiff() { | |
tmpfile=`mktemp` | |
OLD_IFS=$IFS; | |
IFS=$'\n' | |
declare -A left; | |
declare -A right; | |
#Read files into arrays | |
for i in `cat "$1"`; | |
do | |
v="`echo $i | awk -F '[= ]+' '{print $2;}' | sed 's/\r//g;'`" | |
if [ -z $v ]; | |
then | |
v="<null>" | |
fi | |
left["`echo $i | awk -F '[= ]+' '{print $1;}'`"]="$v" | |
done | |
for i in `cat "$2"`; | |
do | |
v="`echo $i | awk -F '[= ]+' '{print $2;}' | sed 's/\r//g;'`" | |
if [ -z $v ]; | |
then | |
v="<null>" | |
fi | |
right["`echo $i | awk -F '[= ]+' '{print $1;}'`"]="$v" | |
done | |
#Printing | |
IFS=$OLD_IFS | |
for k in "${!left[@]}"; | |
do | |
v=${left[$k]}; | |
if [ ${right[$k]} ]; | |
then | |
if [[ "$v" == "${right[$k]}" ]]; | |
then | |
echo "Matches: $k=$v" >> "$tmpfile" | |
else | |
echo "Differs: $k => ${v} _VS_ ${right[$k]}" >> "$tmpfile" | |
fi | |
unset -v right[$k] | |
else | |
echo "Left only: $k=$v" >> "$tmpfile" | |
fi | |
done | |
for k in ${!right[@]}; | |
do | |
v=${right[$k]}; | |
echo "Right only: $k=$v" >> "$tmpfile" | |
done | |
cat "$tmpfile" | sort | |
rm -rf "$tmpfile" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment