0

How can I escape a single quote in ag when searching for an expression like this one?

ag ''react-redux''

I'm aware that "'react-redux'" is one solution in this scenario, but I'd like a solution that lets me use single quotes. That way I don't have to worry about the complex escape sequences required by $, %, etc. when using double quotes.

achalk
  • 3,229
  • 3
  • 17
  • 37

2 Answers2

2

you can use \x27 to represent single quotes. (\x27 is just the ascii code for single quotes) thus, you can use:

ag '\x27react-redux\x27'

ref: How to escape single quote in sed? --stackoverflow

Dehai Chen
  • 60
  • 7
1

While \x27 works, it's obscure. The standard approach is triple single quotes. So, if you want to escape single quotes around 'react-redux' you'd surround each single quote with a pair of single quotes: '''react-redux'''. For example:

$ag '''DD-MON-YYYY''' users.sql
19:       TO_CHAR(lock_date, 'DD-MON-YYYY') AS lock_date,
20:       TO_CHAR(expiry_date, 'DD-MON-YYYY') AS expiry_date,
23:       TO_CHAR(created, 'DD-MON-YYYY') AS created,

So, a trivial example to only match quoted items:

$touch test.txt
$echo value >> test.txt
$echo '''value''' >> test.txt
$echo value >> test.txt
$ < test.txt 
value
'value'
value
$ ag '''value''' test.txt
2:'value' 
gregory
  • 10,969
  • 2
  • 30
  • 42
  • When I try this I get all occurrences of `react-redux`, quotes or no quotes. – achalk Jun 04 '18 at 20:06
  • Then something in your shell is interfering, this should ONLY match quoted items. I'll provide an example in the main answer. – gregory Jun 04 '18 at 20:24
  • Try ag \'react-redux\' – gregory Jun 04 '18 at 20:38
  • Works, but then I can't use regex syntax. – achalk Jun 04 '18 at 20:53
  • @adc17, Which of my suggestions works? And why can't you use regex syntax -- where/how are you using it? – gregory Jun 04 '18 at 22:17
  • e.g. I can't use `ag \'react-red.*\'` – achalk Jun 05 '18 at 01:42
  • 2
    @adc17, of course you can, just enclose the pattern in double quotes. For example ag "\'react-red.*\'"' – gregory Jun 06 '18 at 05:54
  • ...but if you *really* need to only use single quotes with regex, then follow this pattern: single quote the pattern and double quoting single quotes inside the pattern, for example: ag '''DD-MON-YYYY''[\)\sA-z]*' would match: 'DD-MON-YYYY' ) AS created, -- note, this is just a variant on the triple single quote recipe I mentioned above. – gregory Jun 06 '18 at 06:12
  • Double-quotes works. When I asked the question, I'd had trouble using special regex chars like ^ and $ with double quotes, but it seems to be working fine now. – achalk Jun 06 '18 at 15:17