Tuesday, October 25, 2022

[SOLVED] BASH_REMATCH with / character

Issue

Hi I have a text file like this:

# mysite.online (host ok)
192.168.0.10,0
192.168.1.3,0
# mysite.ch (host ok)
192.168.0.11
192.168.1.4
# mysite2.online (host ok)
192.168.0.12
192.168.1.9
# mysite2.ch (host ok)
192.168.0.13
192.168.1.11
# mysite.ch/home.html (url ok)
192.168.0.15
192.168.1.169

I need to read the single line and capture the hostname and the IP: I'm using this code:

while read -r line
  do
    if [[ $line =~ ([a-zA-Z0-9.-]+)\ \((host|url)\ ok\) ||
      $line =~ ([0-9]+(\.[0-9]+){3})\ \(IP\ ok\) ]]; then
      host="${BASH_REMATCH[1]}"
    elif [[ $host != "" ]]; then
      if [[ $line =~ ^([0-9]+(\.[0-9]+){3}) ]]; then
        ip="${BASH_REMATCH[1]}"
        check_site $host $ip
      fi
    fi
  done < <(echo -e "$chunk") &

But I have a problem to capture host when there is a / character, for example the host
# mysite.ch/home.html (url ok) returns only home.html and not mysite.ch/home.html.

How can fix it?


Solution

Change this line:

 if [[ $line =~ ([a-zA-Z0-9.-]+)\ \((host|url)\ ok\) ||
          $line =~ ([0-9]+(\.[0-9]+){3})\ \(IP\ ok\) ]]; then

to this:

 if [[ $line =~ ([a-zA-Z0-9./-]+)\ \((host|url)\ ok\) ||
          $line =~ ([0-9]+(\.[0-9]+){3})\ \(IP\ ok\) ]]; then


Answered By - Swifty
Answer Checked By - Cary Denson (WPSolving Admin)