replace worded digits closest to edges of line

This commit is contained in:
ida schmidt 2023-12-01 21:23:47 -07:00
parent 02f571062e
commit 065b24248e

36
day1.sh
View file

@ -12,13 +12,37 @@ num[9]=nine
declare -a val # make array to hold values
cat $1 | while read l; do # read standard input
((i++)) # increment index
echo before transform: $l
for n in {1..9}; do
l=`echo $l | sed "s/${num[$n]}/$n/g"`
li="$l"
for ni in {1..9}; do # ascend through worded digits
li=`echo $li | sed "s/${num[$ni]}/$ni/g"`
done
echo after transform: $l
first=`echo $l | grep -E -o '^[a-z]*?[0-9]' | grep -o [0-9]`
last=`echo $l | grep -E -o '[0-9][a-z]*?$' | grep -o [0-9]` # extract the first and last number from the line
ld="$l"
for nd in {9..1}; do # ... and descend
ld=`echo $ld | sed "s/${num[$nd]}/$nd/g"`
done
lifd=`echo $li | grep -E -o '^[a-z]*?[0-9]'` # select distance to first match, ascending
ldfd=`echo $ld | grep -E -o '^[a-z]*?[0-9]'` # then descending
if [[ ${#ldfd} -lt ${#lifd} ]]; then # compare first match's distance
bf=$ld
else
bf=$li
fi
ldld=`echo $ld | grep -E -o '[0-9][a-z]*?$'` # select distance to last match, ascending
lild=`echo $li | grep -E -o '[0-9][a-z]*?$'` # then descending
if [[ ${#ldld} -lt ${#lild} ]]; then # compare last match's distance
bl=$ld
else
bl=$li
fi
first=`echo $bf | grep -E -o '^[a-z]*?[0-9]' | grep -o [0-9]`
last=`echo $bl | grep -E -o '[0-9][a-z]*?$' | grep -o [0-9]` # extract the first and last number from the line
val[$i]=`echo "($first*10)+$last" | bc` # assign combined number to the array at current index
echo ${val[$i]}
echo -n total: