Mario
Mario

Reputation: 9

Isolate last non 0 digit from IP address

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?

Upvotes: -1

Views: 63

Answers (4)

Ed Morton
Ed Morton

Reputation: 204381

This might be what you're trying to do:

terminal_ip="$(sed -n 's/.*TERMINAL_IP *= *//p' def.cfg)"
[[ "$terminal_ip" =~ ^.*([1-9])0*$ ]]
last_digit="${BASH_REMATCH[1]}"

and of course if you ONLY need that digit then you could just do:

last_digit="$(sed -n 's/.*TERMINAL_IP *= .*\([1-9]\)0*$/\1/p' def.cfg)"

Upvotes: 0

Mario
Mario

Reputation: 9

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.

Upvotes: -1

choroba
choroba

Reputation: 242123

If you're already using grep -P, you can use it to extract the last non-zero digit, too:

last_digit=$(grep -Po '(?<=TERMINAL_IP = ).*' "$CONFIG_FILE" \
             | grep -Po '[1-9](?=0*$)')

Note that $last_digit will be empty if the IP ends in .0.

Also note that I didn't use upper case letters for a non-environment variable.

Upvotes: 0

Cyrus
Cyrus

Reputation: 88839

With GNU bash and its Parameter Expansion:

TERMINAL_IP="192.168.0.140"
TERMINAL_IP="${TERMINAL_IP/%0/}" # remove an existing trailing 0
echo "${TERMINAL_IP: -1:1}"      # extract last digit

Output:

4

Space before -1 is important.

Upvotes: 1

Related Questions