Apoorv Khurasia Apoorv Khurasia - 1 month ago 5x
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`

is a reserved character in Perl. How can I escape
does not work.


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'


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


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

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 ...