Perl/sed Escape Syntax Problem . . .

Greetings!

I've run into this before; and am having a spot of trouble trying to figure out the way that Perl would prefer the following example syntax to be formed:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

`sed -i 's/Hi Mom!\|Hi Dad!/Bye Everyone!/I' ./test.txt`;

Perl doesn't throw a fit; but sed simply looks at you funny and does nothing at all...

So, while there are "sleeker" ways of handling this with pure perl, this type of issue has bugged me for a bit. Any ideas as to how one might pull things together syntaxwise to make it tick over???

:rolleyes:

Thanks for the help, and have a great day!

Try:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

`sed -i 's/Hi Mom!\\|Hi Dad!/Bye Everyone!/I' ./test.txt`;
1 Like

You need two \\ because...
perl passes one \ to a shell,
the shell finds the \ within a 'string' and leaves it unchanged,
sed finds \|
Bingo.
If the shell would find the \ outside a 'string' it would quote the next character, so you would need \\\\ in your perl code -> Perl passes \\ to the shell -> the shell passes \ to sed -> sed finds \|
You should really do that in Perl...

1 Like

Thanks, folks, for the clarifications and input.

Thanks, MadeInGermany, for the smile. I do agree; but I also truly love Monty Python :wink:

Thanks again; and have a great weekend!

You can also do something like this:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

qx'sed -i "s/Hi Mom!\|Hi Dad!/Bye Everyone!/I" ./test.txt';

No more double backslash, but you have to change the quote character in the sed command.

1 Like

@bartus11:

Interesting and helpful!

What are we doing here; and what are the pros & cons of using this approach???

:rolleyes: