问题描述
我想与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.
抱歉,=
之后的值可能是多字值.
sorry, values after =
could be multi-word values.
推荐答案
我可能是错的,但是在快速阅读,尤其是页面末尾的注2,当与点运算符匹配时,bash有时会包含换行符.因此,一种快速的解决方案是:
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 =)
此外,如果我理解正确,^或$实际上会(分别)匹配字符串的开头或结尾,而不是行.最好由其他人确认,但是确实如此,并且您确实想按行进行匹配,您需要编写一个while循环以逐行读取每一行.
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.
这篇关于bash中的多行正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!