Click to See Complete Forum and Search --> : perl sed and s// with a $var


lrhogusa
01-23-2003, 10:55 PM
Has any one put a $var in a sed s// command?

Something like this:

$pd = "whatever";
$cmd = "/bin/sed"
. "-e 's/text/$pd/g' "
. " /home/lrhog/test.cfg >/home/lrhog/test.txt ";
system "$cmd";

This stuff works ok if I replace $pd with text stuff but with $pd it's no good.

Thank you,
Roy

takshaka
01-23-2003, 11:46 PM
Why on earth would you want to call sed from Perl (or for that matter, spawn a subshell to do anything Perl can do natively)? Text manipulation is Perl's forte.
my $pd = 'whatever';
open my $infile, '/home/lrhog/test.cfg' or die "Can't open input file: $!";
open my $outfile, '>/home/lrhog/test.txt' or die "Can't open output file: $!";

while (<$infile>) {
s/text/$pd/g;
print $outfile $_;
}

close $outfile;
close $infile;

While a Bad Idea, your example should work unless $pd contains unescaped text that can't normally appear on the right side of a sed replacement expression. That is, variable interpolation is done before the command line is sent to the shell, so if you have unescaped slashes or something in $pg, sed will crap out.

lrhogusa
01-26-2003, 04:16 AM
The reason is perl newbie ignorance for not doing stuff efficiently.

Thank you for your help with the code.

Roy

RichMac
01-26-2003, 05:47 AM
on the same kind of topic

how would one direct output to a filename thats a variable? like I tried

commands > $var

and of course it says ambigious redirect, any way?

lrhogusa
01-28-2003, 09:46 PM
Here's a perl newbie ignorant command stuff

$shadowline = `/bin/grep ^user: /etc/shadow`;

That makes $shadowline the value of the output of a grep command

or

my $cmd = "/usr/sbin/userdel";

That makes $cmd the userdel command without the user in it. The following might work, I am guessing being new at this.

my @user = qw(perl, java, basic);
my $cmd = ("/usr/sbin/userdel","-r",$user);
foreach $user (@user)
{
while (1)
{
`$cmd`; #those little slants are back ticks
print "So long $user\n";
}
}
exit;

Hena
01-30-2003, 03:06 AM
I would point out the man pages for perl. They seem to be very good ("man perl").