Multiline regex in bash

I would like to make some multi-line matches with bash =~

 #!/bin/bash str='foo = 1 2 3 bar = what about 42? boo = more words ' re='bar = (.*)' if [[ "$str" =~ $re ]]; then echo "${BASH_REMATCH[1]}" else echo no match fi 

Almost there, but if I use ^ or $ , it will not match, and if I do not use them ^ will also use newline characters.

EDIT:

Sorry, the values ​​after = can be verbose.

+7
source share
1 answer

I could be wrong, but after a quick read from here , especially in note 2 at the end of the page, bash can sometimes include a newline when matching with a dot operator. Therefore, a quick solution would be the following:

 #!/bin/bash str='foo = 1 bar = 2 boo = 3 ' re='bar = ([^\ ]*)' if [[ "$str" =~ $re ]]; then echo "${BASH_REMATCH[1]}" else echo no match fi 

Note that I am now asking that this matches anything other than newlines. Hope this helps =)

Edit: Also, if I understood correctly, then ^ or $ actually correspond to the beginning or end (respectively) of the line, not the line. It would be better if someone else could confirm this, but it is, and you want to combine the lines, you need to write a while loop for each line separately.

+10
source

All Articles