#!/bin/bash # Find valid calls of mul(), do(), and don't() function_calls=$(cat input.txt | grep -e 'mul([[:digit:]]\+,[[:digit:]]\+)' -e 'do()' -e "don't()" -o) mul () { # Takes a string of number1,number2 and multiplies them. local multiplicand=$(echo $1 | cut -d , -f 1) local multiplier=$(echo $1 | cut -d , -f 2) echo $((multiplicand * multiplier)) } total=0 doing=1 # Loop over the function calls and execute them. Need -0 to ignore single quotes. for call in $( echo $function_calls | xargs -0 ); do if [ $call == 'do()' ]; then doing=1 elif [ $call == "don't()" ]; then doing=0 elif [ $doing -eq 0 ]; then continue else args=$(echo $call | sed 's/mul(//g' | sed 's/)//g') product=$(mul $args) total=$((total + product)) fi done echo $total