Search code examples
shelldouble-quotessingle-quotes

bash: matching single and double quotes together by grep


The target is to match single- or double-quotes words in the text.

'foo'
"bar"
'buz"
# text

In the bash script from the book named Classic Shell Scripting (script 1), escaping quotes is required. How to do that?

#! /bin/sh - 
grep \(["']\).*\1 text
# script 1

An alternative solution (script 2) is .

#! /bin/sh -
grep -e "'.*'" -e '".*"' text
# script 2

The exact solution (script 3) by @William Pursell is more compact.

#! /bin/sh - 
grep '\(["'"']\).*\1" text
# script 3

Solution

  • I am probably mis-interpreting the question, but it seems like you are asking how to deal with properly escaping the quotes. Just do:

    grep '\(["'"']\).*\1.*\1"