Search code examples
bashperl

Perl one-liner regex doesn't substitute correctly - returns error


This is probably something kick-self obvious but I have to ask as I'm not seeing it.

I'm trying to make the following substitution in this text file. I want this:

bind_password = 'grafana'

to become this:

bind_password = ''

I've tried using the following regex one-liner on the file that contains the line:

$ perl -0pe 's/(bind_password = \')grafana\'/$1\'/g' file.txt
bash: syntax error near unexpected token `)'

When I've tried the regex on regex101, it's worked fine: https://regex101.com/r/0fb4Pu/1. The difference is that I've had to escape the single quotes. I've tried using double quotes instead of single around the regex, as in:

perl -0pe "s/(bind_password = ')grafana'/$1'/g" file.txt

But while this doesn't return an error, it doesn't do what I want. It instead replaces the string with a single colon, like so:

'

What am I doing wrong here?


Solution

  • You can use

    perl -i -pe "s/bind_password = '\Kgrafana(?=')//" file.txt
    

    Details:

    • -i - modify the file contents
    • bind_password = '\K - match bind_password = ' and remove this text from the match value (so that it stays intact in the file)
    • grafana - your grafana word
    • (?=') - followed with ' (but ' is not consumed, so it stays in the file intact)

    Note:

    • You do not need 0 in -0pe because your match is not spanning multiple lines
    • Escaping single quotes does not work like this, it is simpler to use dobule quotes here around the expression, although sometimes concatenation is the only way to go
    • You need no g flag since this perl works on a line-by-line basis, and processes all lines (g is necessary when there are multiple matches per line).