replace string in file

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I want to replace a key word in a file with a string.  Here is a
segment of code cut out of a script I wrote to help me generate
desktop application links.

open TEMPLATE, './template.desktop' or
    die("could not open template.desktop file\n");
my @template = <TEMPLATE>;
foreach (@template)
open OUTFILE, ">$ENV/Desktop/$ARGV[2]" or
    die("could not open output file\n");
print OUTFILE @template;
close OUTFILE;

I was just wondering if there was a better way.

Thank you to all for help on this question and all previous questions
I have submitted to this group for which all responses and
particularly certain special responses have been most helpful.


Re: replace string in file

Quoted text here. Click to load it

This is such a common use for perl that there's a couple command line
arguments available to make this a one-liner:

perl -pe"s/EXEC/arg0/; s/NAME/arg1/;" ./template.desktop >

Read about -p and -e in
perldoc perlrun

You may also be interested in -i, also in the above perldoc.

Paul Lalli

Re: replace string in file

Paul Lalli wrote:

Quoted text here. Click to load it

The /g modifier is still required; "EXEC" could appear multiple times on one
line as could "NAME".

Re: replace string in file

wana wrote:
Quoted text here. Click to load it

There is on point in reading the whole file into an array when afterwards
you are looping through each line individually anyway. Better process each
line as you read it:

while (<TEMPLATE>) {.....


Re: replace string in file

wana wrote:

Quoted text here. Click to load it

Just an idea: You could use STDIN and STDOUT instead of opening
filehandles. I don't know if this is a good idea, that belongs to
your scenario. You could cut it down to (untested):

  use warnings;
  use strict;
  use diagnostics;

  while(<>) {

If you want to use a default file (eg. ./template.desktop) you could
use this one (again untested):

  [...she-bang and use's...]

  open TPL, '<./template.desktop'
    or die('Unable to open template file.'."\n");
  while(<TPL>) {
  close TPL;

You can use this one by running
  $ $SCRIPT exec_replace name_replace > file

The pro I see here is that you're not doing any buffering of the complete
content of the input file.


-- /

»Better to reign in hell than to serve in heaven«
                             -- John Milton, »Paradise Lost«

Site Timeline