[ale] sed

Jamey Owens vindir at comcast.net
Thu May 17 21:44:59 EDT 2007


One note of caution.  It can be pretty dangerous to try and use the same 
file for input and output.  Lots of shells will leave you with a totally 
empty file using the previous sed command with input & output being equal.

For adding the equivalent of #2 to your script you can use some derivative 
of the example below.  Would be faster and safer to use a string/array to 
rebuild the whole file in memory before writing to the filehandle instead of 
using a temp file if you're sure you'll only be using it on smaller files.

If you really want to use sed from your perl script you would just use the 
sed command inside a system() call.

example:
my $filename = "/pathto/yourfile.ext";

open (TempFile, ">>$filename.tmp");
open (MainFile, "$filename");

while (<MainFile>) #Step through your file line at a time
{
    #Replace the current line with the new one with matching regex
    $_ =~ s/abc/xyz/g;
    print TempFile $_;
}

system("mv $filename.tmp $filename");
close(TempFile);
close(MainFile)


Good Luck,
JO

----- Original Message ----- 
From: "cfowler" <cfowler at outpostsentinel.com>
To: ale at ale.org
To: "Atlanta Linux Enthusiasts" <ale at ale.org>
Sent: Thursday, May 17, 2007 7:57 PM
Subject: Re: [ale] sed


> Your subject is SED but Perl in body.
>
> #1. Sed
> sed 's/abc/xyz/g' < input > output
>
> #2 Perl
> perl -e 'while(<>) { s/abc/xyz/g; }' < input > output
>
> On Thu, 2007-05-17 at 19:43 -0400, Terry Bailey wrote:
>> Hi,
>>
>> I want to take a text file and replace each occurrence of abc with
>> xyz.  I know that this can be done with an editor like nano; however,
>> I want to do this within a Perl script.   I think sed can be used to
>> do this and I have known about it since my UNIX days, but have never
>> used it. Can anyone tell me what the syntax would be?
>>
>> Thanks,
>>
>> Terry Bailey
>>
>> _______________________________________________
>> Ale mailing list
>> Ale at ale.org
>> http://www.ale.org/mailman/listinfo/ale
>
> _______________________________________________
> Ale mailing list
> Ale at ale.org
> http://www.ale.org/mailman/listinfo/ale 




More information about the Ale mailing list