bash bash中的多行正则表达式匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12619720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:23:50  来源:igfitidea点击:

multiline regexp matching in bash

bashpattern-matching

提问by pihentagy

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

我想用 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 don't use them, .eats newlines too.

差不多了,但是如果我使用^or $,它将不匹配,如果我不使用它们,.也会吃换行符。

EDIT:

编辑:

sorry, values after =could be multi-word values.

抱歉,后面的值=可能是多字值。

回答by Janito Vaqueiro Ferreira Filho

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:

我可能是错的,但是从这里快速阅读之后,尤其是页面末尾的注释 2,bash 在与点运算符匹配时有时会包含换行符。因此,一个快速的解决方案是:

#!/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.

编辑:另外,如果我理解正确, ^ 或 $ 实际上将匹配字符串的开头或结尾(分别),而不是行。如果其他人可以确认这一点会更好,但情况确实如此,并且您确实希望按行匹配,您需要编写一个 while 循环来单独读取每一行。