0

I've been out of programming for more than 10 years. I have a text file that I'm trying to read the Mpbs value for the upload and download speed.

     Server: Iomart - Maidenhead (id = 3839)
        ISP: Plusnet
    Latency:     8.59 ms   (0.10 ms jitter)
   Download:    71.43 Mbps (data used: 52.8 MB)                               
     Upload:    18.39 Mbps (data used: 16.9 MB)                               
Packet Loss:     0.0%

I've been using a regex tool to test and build my regex, which delivers the result I want.

regex2="Upload:\W+([0-9]+\.[0-9]+)"
regex3="Download:\W+([0-9]+\.[0-9]+)"

while read line; do  
    if [[ $line =~ regex2 ]]
    then
        echo  "match ${BASH_REMATCH[1]}"
        UPS=${BASH_REMATCH[1]}
    fi  
    if [[ $line =~ regex3 ]]
    then
    echo  "match ${BASH_REMATCH[1]}"
        DNS=${BASH_REMATCH[1]}
    fi 
done < Result.txt

I'm sure there must be a better way to achieve what I want, but the main problem I'm having is the regex not working.

Kusalananda
  • 333,661

1 Answers1

0

You have three issues in your code.

  1. You're not using the regular expressions you think you are (missing $ on regex2 and regex3).
  2. bash does not understand the Perl-like regular expression \W as "not a word character".
  3. You are not reading lines (even though your variable is called line).

To solve this:

  1. Use $ on to get the values of regex2 and regex3 in the tests:

    if [[ $line =~ $regex2 ]]; then ...; fi
    
  2. Use the POSIX regular expression [^[:alnum:]_] in place of \W in the expressions, or [[:blank:]] which matches a tab or space.

  3. Use while IFS= read -r line; do ...; done (see "Understanding "IFS= read -r line"").

Kusalananda
  • 333,661