#!/usr/bin/env bash INPUT_RULES=$(sort -n input-rules) { while read -r LINE do GREP_EXPR=$( printf "%s" "$LINE" | tr ',' '|' ) BEEG_AWK_EXPR=$( printf "%s" "$INPUT_RULES" | grep -E "($GREP_EXPR)\\|($GREP_EXPR)" | sed -E 's/(.*)\|(.*)/\1,.*\2/; s&^&/&; s&$&/&' | paste -s -d '@' | sed 's/@/ \&\& /g' ) AWK_MATCH=$( printf "%s" "$LINE" | awk "$BEEG_AWK_EXPR" | wc -c ) # Don't process for valid lines if [[ $AWK_MATCH -gt 0 ]] ; then continue; fi 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 '|' ) read -r -a 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 0 ]] ; then break ; fi done printf "%s\n" "$KEY" CACHED_LINE=$( printf "%s" "$CACHED_LINE" | grep -v "$KEY" ) done | tac | paste -s -d' ' done } | awk ' BEGIN{ total = 0 } { if (NF % 2 == 1) { idx = int( NF / 2 ) + 1 } else { idx = NF / 2 } total += $idx } END{ print total }'