Skip to content

Instantly share code, notes, and snippets.

@nemasu
Last active October 11, 2015 22:03
Show Gist options
  • Save nemasu/b2c8a9795b3cd8233ccc to your computer and use it in GitHub Desktop.
Save nemasu/b2c8a9795b3cd8233ccc to your computer and use it in GitHub Desktop.
Bash function that compares files containing key-value pairs.
#$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