在bash中的正则表达式中的字符串变量?

问题描述:

我必须在shell脚本中编写一个正则表达式来获取另一个字符串中的字符串,以便我的变量字符串myString出现在正则表达式字符串中。我怎样才能做到这一点?在bash中的正则表达式中的字符串变量?

+0

如果你告诉更多你想要做什么,这将有助于。 “take myString”是什么意思?做myString改变,什么是你希望匹配的表达式的上下文中的常量? – CharlesB

+0

@CharlesB我编辑了我的问题。你可以看一下吗? – Larry

+0

*“myString是一个常量字符串”* ...除非我在这里丢失了某些东西,如果您匹配一个常量字符串,则不需要正则表达式。你是否试图提取双引号内的所有内容?双引号之外的文本是否保持不变? –

grep是在shell中查找正则表达式的最常用工具。

+0

yeap,我知道我可以像这样使用grep:grep -P'。*“。*”。 *'-o [文件]但是,我想要在双引号内取得字符串。 @Bitwise – Larry

如果你想在双引号中提取文本,并假设只有有一对双引号,这样做的一个方法是:

[[email protected]]$ echo $A 
to get "myString" in regular expression 
[[email protected]]$ echo $A | sed -n 's/.*"\(.*\)".*/\1/p' 
myString 

当然,如果只有一组引号你也可以不用SED /正则表达式:

[[email protected]]$ echo $A | cut -d'"' -f2 
myString 
+0

不错:)。我知道了。 – Larry

>echo 'hi "there" ' | perl -pe 's/.*(["].*["])/\1/g' 
"there" 

如果你知道只会有一组双引号的,你可以使用shell parameter expansion这样的:

zsh> s='to get "myString" in regular expression' 
zsh> echo ${${s#*\"}%\"*} 
mystring 

的bash不支持多级扩展,所以扩展需求相继被应用:

bash> s='to get "myString" in regular expression' 
bash> s=${s#*\"} 
bash> s=${s%\"*} 
bash> echo $s 
mystring 

您还可以使用 'AWK':

echo 'this is string with "substring" here' | awk '/"substring"/ {print}' 

# awk '/"substring"/ {print}' means to print string, which contains regexp "this" 

在bash中,你可以在[[ ... ]] conditional construct中使用=〜运算符,与BASH_REMATCH variable一起使用。使用

例子:

TEXT='hello "world", how are you?' 
if [[ $TEXT =~ \"(.*)\" ]]; then 
    echo "found ${BASH_REMATCH[1]} between double quotes." 
else 
    echo "nothing found between double quotes." 
fi