2

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?

4
  • 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? Commented Sep 17, 2012 at 9:21
  • Out of which String? Possibly this helps Commented Sep 17, 2012 at 9:22
  • @CharlesB I edited my question. Could you please take a look ? Commented 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? Commented Sep 17, 2012 at 9:29

6 Answers 6

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

You can also use 'awk':

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

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

Comments

0

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

Comments

-1

grep is the most common tool for finding regular expressions in the shell.

1 Comment

yeap, I know I can use grep like this : grep -P '.*".*".*' -o [FILE] however, I wanna to get string inside double quotes. @Bitwise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.