Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all matches from regex?

Tags:

regex

bash

shell

I would like to get all occurrences of [0-9A-Z]+? for processing later. I do have

if [[ `cat file` =~ '[0-9A-Z]+?' ]]; then
  echo $BASH_REMATCH;
fi

Which gives me first match, but how could I process all the matches in the file?

Thank you

like image 768
mike Avatar asked Mar 13 '09 10:03

mike


1 Answers

If you want to get just the matched text of a regular expression, I would use

grep -o 'regex' file

In the spirit of your code I would modify it to be

while read line; do
    [[ $line =~ regex ]] || continue
    # do somethinw with $line or $BASH_REMATCH, perhaps put it in an array.
done < file

If you want to match multiple regexes on the same line, here is a way.

while read line; do
    # do somethinw with $line
done < <(grep -o 'regex' file)

I assume your regex is supposed to be a simplified example of what your really doing. The ? is not helpfull and your quotes are matching a literal string.

like image 188
Ian Kelling Avatar answered Sep 20 '22 03:09

Ian Kelling