views:

361

answers:

2

Hi,

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

A: 

Sounds like a job for regex!

James Anderson
+3  A: 

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.

Ian Kelling
The regex is slightly more complex, +? is needed to be lazy.Even though the "while ... done < file" is what I needed, greatly appreciated, didn't know where to look.Thank you
michal kralik
What if one line contains the regex match twice?How can I process that?
michal kralik
see updated answer
Ian Kelling