1

I made this batch script that is parsing a file and displaying my values if found :

#!/bin/bash
myFile="my-services.log"
while read p; do
    re="(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3}).*:(\d*)"
    if [[ $p =~ $re ]]; then 
        echo ${BASH_REMATCH[0]} 
        echo ${BASH_REMATCH[1]}
        echo ${BASH_REMATCH[2]} 
    fi
done <$myFile

My log file contains things like this

2017-03-24 07:51:43,368 my log id :469565

My script runs well, but doesnt match anything even with data that are matching my regex. I checked my regex with my file editor and it is finding occurrences, so it is strange.

Please note that I was highly insprired from Regular Expression in Bash Script and Multiple matches in a string using regex in bash

3
  • 2
    Are you sure that bash supports \d? Commented Mar 27, 2017 at 14:27
  • wow didn't thought about it. Well done, juste had to replace all \ by their real values such as [0-9] for \d. Many thanks, please post an answer so I validate it Commented Mar 27, 2017 at 14:30
  • Just accept the existing answer by whjm ;) :) Commented Mar 27, 2017 at 14:36

1 Answer 1

2

Bash does not support \d, \s.

[STEP 100] $ echo $BASH_VERSION
4.4.12(3)-release
[STEP 101] $ d4='[[:digit:]]{4}'
[STEP 102] $ d2='[[:digit:]]{2}'
[STEP 103] $ d3='[[:digit:]]{3}'
[STEP 104] $ ds='[[:digit:]]+'
[STEP 105] $ re="^($d4-$d2-$d2 $d2:$d2:$d2,$d3) .*:($ds)\$"
[STEP 106] $ str='2017-03-24 07:51:43,368 my log id :469565'
[STEP 107] $ [[ $str =~ $re ]]
[STEP 108] $ echo $?
0
[STEP 109] $ echo ${BASH_REMATCH[1]}
2017-03-24 07:51:43,368
[STEP 110] $ echo ${BASH_REMATCH[2]}
469565
[STEP 111] $
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.