I have to read an IP from def.cfg file that is set in a line named TERMINAL_IP (TERMINAL_IP = "192.168.0.140"), then do an append to the end of the def.cfg file with the last digit read that is not a 0 number, in this example have a 0 in the last digit so the value to show must be 4 and if the last number is .100 the value to show will be 1 but if the last number is .145 the value to show must be 5.
I'm using the following script to do that:
#!/bin/bash
CONFIG_FILE="def.cfg"
TERMINAL_IP=$(grep -oP '(?<=TERMINAL_IP = ).*' "$CONFIG_FILE")
if [[ -z "$TERMINAL_IP" ]]; then
echo "TERMINAL_IP not found in the configuration file."
exit 1
fi
LAST_DIGIT=$(echo "$TERMINAL_IP" | grep -oE '[0-9]+' | tail -n 1)
if [[ "$LAST_DIGIT" == "0" ]]; then
# If the last digit is 0, take the second-to-last digit
LAST_DIGIT=$(echo "$TERMINAL_IP" | grep -oE '[0-9]+' | tail -n 2 | head -n 1)
fi
echo "LSTD = \"${LAST_DIGIT}\"" >> "$CONFIG_FILE"
The problem is that instead append the number 4, it is appending the number 140, for some reason it does not isolate the number 4.
Any ideas to solve this?
I found the solution as follows:
TERMINAL_IP=$(awk -F'=' '/TERMINAL_IP/ {gsub(/ /, "", $2); print $2}' "$CONFIG_FILE" | tail -1)
TERMINAL_IP_LAST_DIGIT=""
for (( i=${#TERMINAL_IP}-1; i>=0; i-- )); do
DIGIT="${TERMINAL_IP:$i:1}"
if [[ "$DIGIT" =~ [0-9] && "$DIGIT" -ne 0 ]]; then
TERMINAL_IP_LAST_DIGIT="$DIGIT"
break
fi
done
Thanks all.