multiline regexp matching in bash

前端 未结 1 1515
刺人心
刺人心 2021-01-02 01:54

I would like to do some multiline matching with bash\'s =~

#!/bin/bash
str=\'foo = 1 2 3
bar = what about 42?
boo = more words
\'
re=\'bar = (.*         


        
相关标签:
1条回答
  • 2021-01-02 02:21

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

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

    Notice that I now ask it match anything except newlines. Hope this helps =)

    Edit: Also, if I understood correctly, the ^ or $ will actually match the start or the end (respectively) of the string, and not the line. It would be better if someone else could confirm this, but it is the case and you do want to match by line, you'll need to write a while loop to read each line individually.

    0 讨论(0)
提交回复
热议问题