我必须在shell脚本中编写一个正则表达式才能在另一个字符串中获取一个字符串,以便我的变量字符串myString
出现在正则表达式字符串中。我怎样才能做到这一点?
问问题
6343 次
6 回答
2
如果要提取双引号内的文本,并假设只有一组双引号,一种方法是:
[me@home]$ echo $A
to get "myString" in regular expression
[me@home]$ echo $A | sed -n 's/.*"\(.*\)".*/\1/p'
myString
当然,如果只有一组引号,您也可以不使用 sed/regex:
[me@home]$ echo $A | cut -d'"' -f2
myString
于 2012-09-17T09:33:48.317 回答
1
如果你知道只有一组双引号,你可以像这样使用shell 参数扩展:
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
于 2012-09-17T10:42:19.123 回答
0
>echo 'hi "there" ' | perl -pe 's/.*(["].*["])/\1/g'
"there"
于 2012-09-17T10:34:30.523 回答
0
你也可以使用'awk':
echo 'this is string with "substring" here' | awk '/"substring"/ {print}'
# awk '/"substring"/ {print}' means to print string, which contains regexp "this"
于 2012-09-17T10:55:41.720 回答
0
在 Bash 中,您可以在[[ ... ]]条件构造中使用=~运算符以及BASH_REMATCH变量。
使用示例:
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
于 2016-09-27T19:59:13.313 回答
-1
grep是在 shell 中查找正则表达式的最常用工具。
于 2012-09-17T09:27:04.300 回答