Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to extract ALL matches of a regex pattern

Tags:

bash

shell

I found this but it assumes the words are space separated.

result="abcdefADDNAME25abcdefgHELLOabcdefgADDNAME25abcdefgHELLOabcdefg"

for word in $result
do
    if echo $word | grep -qi '(ADDNAME\d\d.*HELLO)'
    then
        match="$match $word"
    fi
done

POST EDITED

Re-naming for clarity:

data="abcdefADDNAME25abcdefgHELLOabcdefgADDNAME25abcdefgHELLOabcdefg"
for word in $data
do
    if echo $word | grep -qi '(ADDNAME\d\d.*HELLO)'
    then
        match="$match $word"
    fi
done
echo $match

Original left so comments asking about result continue to make sense.

like image 447
Neeladri Vishweswaran Avatar asked Sep 04 '10 18:09

Neeladri Vishweswaran


2 Answers

Edit: answer to edited question:

for string in "$(echo $result | grep -Po "ADDNAME[0-9]{2}.*?HELLO")"; do
  match="${match:+$match }$string"
done

Original answer:

If you're using Bash version 3.2 or higher, you can use its regex matching.

string="string to search 99 with 88 some 42 numbers"
pattern="[0-9]{2}"
for word in $string; do
  [[ $word =~ $pattern ]]
  if [[ ${BASH_REMATCH[0]} ]]; then
    match="${match:+$match }${BASH_REMATCH[0]}"
  fi
done

The result will be "99 88 42".

like image 144
Dennis Williamson Avatar answered Nov 05 '22 22:11

Dennis Williamson


Use grep -o

-o, --only-matching show only the part of a line matching PATTERN

like image 26
Daenyth Avatar answered Nov 05 '22 23:11

Daenyth