Wednesday, October 5, 2022

[SOLVED] ssh sed: -e expression #1, char 26: invalid reference \1 on `s'

Issue

I would like to update code between square brackets with double quotes.

$td[blabla]="x";

to

$td["blabla"]="x";

In read is ok with -r

sed -r -e 's/\[([_a-z1-9]*)]/["\1"]/g' "test.php"

But to write is down

sed -i -e 's/\[([_a-z1-9]*)]/["\1"]/g' "test.php"

sed: -e expression #1, char 26: invalid reference \1 on `s' command's RHS

It seems that the expression is not understood, but why?

Thanks you


Solution

-r similar to -E enables ERE giving you access to extended functionality within your script. The removal of it reverts back to BRE

To fix your second code, you can either escape the parenthesis or readd the -r option to re-enable extended functionality.

$ sed -ri.bak 's/\[([_a-z1-9]*)]/["\1"]/g' test.php

You can also try this sed

$ sed -Ei.bak 's/\[([^]]*)/["\1"/' test.php
$ cat test.php
$td["blabla"]="x";

The -i.bak will also create a backup of your file with .bak extension



Answered By - HatLess
Answer Checked By - Cary Denson (WPSolving Admin)