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.

5
  • 3
    You are trying to match against the literal regex2 and regex3, I think you want $regex2 and $regex3.
    – jesse_b
    CommentedApr 8, 2020 at 13:02
  • oops.. Thanks very much. That was a bad cut and paste. now the problem is the \W+ doesn't work. If i just leave the correct number of spaces(four in this case) in the regex2 variable it'll match. is \W or \s not the right way to go? i've tried using \ \\ \\\ and \\\\CommentedApr 8, 2020 at 13:13
  • \W is a PCRE feature - bash only claims to support ERE. I suspect that (especially on MacOS) the bash version doesn't recognize \W (or treats it as literal W). You could consider using [[:blank:]] instead to match horizontal whitespace (unless you specifically expect other non-word characters between the : and the number)CommentedApr 8, 2020 at 13:27
  • ... see also Why does my regular expression work in X but not in Y?CommentedApr 8, 2020 at 13:28
  • The PCRE \W is the same as POSIX [^[:alnum:]_].
    – Kusalananda
    CommentedApr 8, 2020 at 15:09

1 Answer 1

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"").

2

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.