Om Sao
Om Sao

Reputation: 7643

UNIX: Using a regex that matches either single or double quotes with grep

I have a string say

string="MYSTRING"

Now I want to grep for any occurrence of "MYSTRING" (with double quotes) such that there must be parentheses at starting, basically I want to search, in which places "MYSTRING" is used as function's parameter. So,

foo( "MYSTRING"    //postive
foo("MYSTRING"      //positive
foo('MYSTRING'      //positive
foo( 'MYSTRING'      //positive
var a = "MYSTRING"  //negative

I used:

string="MYSTRING"
regexstring="[(]*\"$string\""
grep -e "$regexString" <<'EOF'
foo( "MYSTRING"    //postive
foo("MYSTRING"      //positive
foo('MYSTRING'      //positive
foo( 'MYSTRING'      //positive
var a = "MYSTRING"  //negative
EOF

Ideally, all the items with "positive" next to them and none of the items with "negative" will match. What needs to change to make that happen?

Upvotes: 0

Views: 314

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295373

The easy way to do this is to use the ksh extension (adopted by bash) $'' to provide a literal string that can include backticks.

#!/usr/bin/env bash
string=MYSTRING
regexstring=$'[(][[:space:]]*[\'"]'"$string"$'[\'"]'
grep -e "$regexstring" "$@"

Breaking down this assignment:

$'[(][[:space:]]*[\'"]'

...is a string literal which evaluates to the following:

[(][[:space:]]*['"]

...thus, it matches a single (, followed by zero or more spaces, followed by either ' or ".

The second part of it is a double-quoted expansion, "$string"; this should be fairly straight on its face.

The final part is $'[\'"']'; just as in the first part, the $'' string-literal syntax is used to generate a string that can contain both ' and " as contents.


By the way -- in POSIX sh, this might instead look like:

regexstring='[(][[:space:]]*['"'"'"]'"$string""['"'"]'

There, we're using single-quoted strings to hold literal double quotes, and double-quoted strings to hold literal single quotes.

Upvotes: 1

Related Questions