Apoorv Khurasia Apoorv Khurasia - 3 months ago 7
Perl Question

Use ~ in Perl search and replace

I want to replace a placeholder in all files under a directory with a string that is generated from user input. This input can contain

/ : . ~


I chose Perl for this task.

perl -p -i -e "s/__MY_PLACEHOLDER__/$user_input/g" `find my_dir -type f -print0 | xargs -0`


Now,
~
is a reserved character in Perl. How can I escape
~
in
$user_input
?
\~
does not work.

Answer

Actually, ~ is not special in double-quote string literals such as the replacement expression of s///. Many others are, however. Of the four characters you listed, / is special when / is used as the delimiter as is the case here.


Don't try to generate Perl code from the shell! Use one of the following:

export $user_input
perl -i -pe's/__MY_PLACEHOLDER__/$ENV{user_input}/g'

or

USER_INPUT=$user_input perl -i -pe's/__MY_PLACEHOLDER__/$ENV{USER_INPUT}/g'

or

perl -i -pe'
   BEGIN { $user_input = shift(@ARGV); }
   s/__MY_PLACEHOLDER__/$user_input/g
'

By the way, you really missed the point of xargs!

perl ... `find my_dir -type f -print0 | xargs -0`

is no different than

perl ... `find my_dir -type f`

What you wanted is

find my_dir -type f -print0 | xargs -0 perl ...