- Published on
Compare Two Different Files
526 words3 min read
compare.sh
#!/bin/bash
IFS=$'\n' read -d '' -r -a fileAResource < /tmp/fileA-resource
IFS=$'\n' read -d '' -r -a fileBResource < /tmp/fileB-resource-sco
# FILEA_TOTAL_COUNT holds the total number of resource in FILEA
FILEA_TOTAL_COUNT=0
# FILEA_ORPHANED_COUNT holds the number of orphaned resource
FILEA_ORPHANED_COUNT=0
# FILEA_ORPHANED holds the names of the orphaned resource
FILEA_ORPHANED=()
# FILEB_TOTAL_COUNT holds the total number of resource in FILEB
FILEB_TOTAL_COUNT=0
# FILEB_ORPHANED_COUNT holds the number of orphaned resource
FILEB_ORPHANED_COUNT=0
# FILEB_ORPHANED holds the names of the orphaned resource
FILEB_ORPHANED=()
# Loop through items in fileAResource
for i in "${fileAResource[@]}"; do
EXISTS_IN_FILEB=$(cat /tmp/fileB-resource | grep "$i")
# If the string is null (empty)
if [ -z "$EXISTS_IN_FILEB" ]; then
FILEA_ORPHANED+=("$i")
((FILEA_ORPHANED_COUNT++))
fi
((FILEA_TOTAL_COUNT++))
done
# Loop through items in fileBResource
for i in "${fileBResource[@]}"; do
EXISTS_IN_FILEA=$(cat /tmp/fileA-resource | grep "$i")
# If the string is null (empty)
if [ -z "$EXISTS_IN_FILEA" ]; then
FILEB_ORPHANED+=("$i")
((FILEB_ORPHANED_COUNT++))
fi
((FILEB_TOTAL_COUNT++))
done
if [[ $1 == "fileA-debug" ]]; then
echo "${FILEA_ORPHANED[@]}"
fi
if [[ $1 == "fileB-debug" ]]; then
echo "${FILEB_ORPHANED[@]}"
fi
echo "There are $FILEA_ORPHANED_COUNT (out of $FILEA_TOTAL_COUNT) orphaned resource (resource that exist in FILEA but not FILEB)"
echo "There are $FILEB_ORPHANED_COUNT (out of $FILEB_TOTAL_COUNT) orphaned resource (resource that exist in FILEB but not FILEA)"