#!/usr/bin/env bash { while read -r LINE do GREP_EXPR=$( printf "%s" "$LINE" | tr ',' '|' ) MATCH_COUNT=0 # Loop through rules and find a breaking rule while read -r RULE do GREPC=$( printf "%s" "$LINE" | grep -c "$RULE" ) if [[ $GREPC -ne 1 ]] then #printf "%s rule violated for %s \n" "$RULE" "$LINE" MATCH_COUNT=1 break fi # Filter rules that only has included pages done <<< "$( < input-rules grep -E "($GREP_EXPR)\\|($GREP_EXPR)" | sed 's/|/,.*/')" # Don't process for valid lines [[ $MATCH_COUNT -eq 0 ]] && continue printf "%s\n" "$LINE" done < input-updates } | { while read -r LINE # Generate a hashmap and rebuild the entire line from rules do CACHED_LINE=$( printf "%s" "$LINE" | tr ',' '\n' ) while [[ $( printf "%s" "$CACHED_LINE" | wc -c ) -gt 0 ]] do # Loop through rules and build all the KVs DAG_GREP_EXPR=$( printf "%s" "$CACHED_LINE" | paste -s -d '|' ) KV_ARRAY=( $( < input-rules grep -E "($DAG_GREP_EXPR)\\|($DAG_GREP_EXPR)" | tr '|' ' ' | paste -s -d ' ') ) # Going through dependencies to find final key KEY=${KV_ARRAY[0]} while true do BREAK=0 for (( i=0; i<${#KV_ARRAY[@]}; i+=2 )) # Check if key exists do if [[ ${KV_ARRAY[$i]} -eq $KEY ]] then KEY=${KV_ARRAY[$i+1]} BREAK=1 break fi done if [[ $BREAK -eq 1 ]] ; then continue ; else break ; fi done printf "%s\n" "$KEY" CACHED_LINE=$( printf "%s" "$CACHED_LINE" | grep -v "$KEY" ) done | tac | paste -s -d' ' done } | tee final-output | awk ' BEGIN{ total = 0 } { if (NF % 2 == 1) { idx = int( NF / 2 ) + 1 } else { idx = NF / 2 } total += $idx } END{ print total }'