views:

339

answers:

1

I have a Perl script called replaceUp:

 #!/usr/bin/perl                                          

 search=$1
 replace=$2

 find . -type f -exec perl -p -i -e "s/$search/$replace/g" {} \;

The script does not get loaded. This suggests me that my script is wrong.

How can you make a shell script using Perl?

+10  A: 

The first line should be #!/bin/sh, not #!/usr/local/bin/perl. You are mistaken that that is a Perl script; it is a shell script that calls Perl.

It's also not going to actually work because $search and $replace are not going to get interpolated inside single quotes. Try single quotes inside double quotes.

Or better yet, try my mass search/replace Perl script. I keep a pure-Perl script for this around because, dangerous as mass search/replace is, you don't need multiple levels of shell metacharacter interpretation taking it from dangerous to absolutely lethal.

chaos
Thank you for your answer! -- arg -- my script is horrible as a shell script. As I started my shell with double quotes, the script started to replace and remove everything in my Root. -- I cannot understand what went wrong.
Masi
@Chaos: Is there any way to see what the file removed at my root?
Masi
@Masi: who were you logged in as? User 'root'? If so, silly, silly, silly. Never do exploration of scripts - Perl, shell or any other type - as root; a mistake can be (will be) catastrophic. You use 'root' only when you absolutely must, and only when you are sure that what you're about to do won't cause any problems. That 'find' command, run in a root directory, could do damage to all sorts of file - like /bin/sh and so on. Not a happy situation to be in. Never run anything as root until you're sure it won't do more harm than good! (And don't login as root.)
Jonathan Leffler
@Masi: Well, you can grep for your replacement string, I guess. That's really unfortunate. Obviously you know now, but when you're talking about something as dangerous as mass search and replace, you should always test inside a temporary directory before you try using it on your whole system.
chaos
Thank you for your answers!
Masi
@chaos: It is rather hard to read your Perl script without comments. Have anywhere the same script with comments?
Masi
@Masi: 'Fraid not.
chaos
Single quotes inside double quotes aren't enough here, since this is a regex. I'd suggest exporting the variables in question, then using 's/\Q$ENV{search}\E/$ENV{replace}/g'
bdonlan
That Perl script doesn't need any comments, it is already very readable.
Brad Gilbert