I have to write a regular expression in shell script to get a string inside another string, so that my variable string myString occurs in the regular expression string. How can I do this?
-
it would help if you tell more on what you want to do. what do you mean by "take myString"? do myString change, and what is constant in the context of the expression you want to match?CharlesB– CharlesB2012-09-17 09:21:32 +00:00Commented Sep 17, 2012 at 9:21
-
Out of which String? Possibly this helpsTom Maier– Tom Maier2012-09-17 09:22:03 +00:00Commented Sep 17, 2012 at 9:22
-
@CharlesB I edited my question. Could you please take a look ?Larry– Larry2012-09-17 09:28:05 +00:00Commented Sep 17, 2012 at 9:28
-
"myString is a constant string" ... unless I'm missing something here, you don't need regular expression if you're matching a constant string. Are you trying to extract everything inside the double quotes? Is the text outside the double quotes constant?Shawn Chin– Shawn Chin2012-09-17 09:29:48 +00:00Commented Sep 17, 2012 at 9:29
Add a comment
|
6 Answers
If you want to extract text within the double quotes, and assuming there's only one set of double quotes, one way to do that is:
[me@home]$ echo $A
to get "myString" in regular expression
[me@home]$ echo $A | sed -n 's/.*"\(.*\)".*/\1/p'
myString
Of course, if there's only one set of quotes you can also do without sed/regex:
[me@home]$ echo $A | cut -d'"' -f2
myString
Comments
If you know there will only be one set of double quotes, you could use shell parameter expansion like this:
zsh> s='to get "myString" in regular expression'
zsh> echo ${${s#*\"}%\"*}
mystring
bash doesn't support multilevel expansion, so the expansion needs to be applied sequentially:
bash> s='to get "myString" in regular expression'
bash> s=${s#*\"}
bash> s=${s%\"*}
bash> echo $s
mystring
Comments
In Bash, you can use the =~ operator in a [[ ... ]] conditional construct, together with the BASH_REMATCH variable.
Example of use:
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