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.


while read line; do  
    if [[ $line =~ regex2 ]]
        echo  "match ${BASH_REMATCH[1]}"
    if [[ $line =~ regex3 ]]
    echo  "match ${BASH_REMATCH[1]}"
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.

  • 3
    You are trying to match against the literal regex2 and regex3, I think you want $regex2 and $regex3.
    – jesse_b
    Apr 8 '20 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 \\\\ Apr 8 '20 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) Apr 8 '20 at 13:27
  • The PCRE \W is the same as POSIX [^[:alnum:]_].
    – Kusalananda
    Apr 8 '20 at 15:09

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.