Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All, I know this is pretty simple, but I can not get this to work. I want to substitute all instances of a word contained within a certain file. I have tried this different method:
#perl -ne 's/text/newtext/g' /path/to/file

but whe I cat/more the file, nothing has been substituted.
I have also tried this:
#perl -ne 's/text/newtext/g' /path/to/file > /path/to/newfile

i an trying to edit this instance in several config files, so I would rather edit the file directly (after copying, of course).

Thanks!!

Replies are listed 'Best First'.
Re: simple text substitution.
by rev_1318 (Chaplain) on Dec 15, 2004 at 15:19 UTC
    You are using the wrong switch. The switch you are looking for is not -n but -p. If you want the file to be edited in place, use the -i switch.

    As an example: to change all occurances of foo in bar in a file:

    perl -pi -e 's/foo/bar/g' file

    See perlrun for more on perl command switches.

    HTH,
    Paul

Re: simple text substitution.
by gellyfish (Monsignor) on Dec 15, 2004 at 15:13 UTC

    perl -pi -e 's/text/newtext/g' /path/to/file

    /J\

Re: simple text substitution.
by sauoq (Abbot) on Dec 15, 2004 at 17:42 UTC

    Your question has already been answered but I thought someone should clue you in to how -i works and why the suggestion was to use perl -pi -e rather than perl -pie which seems, at first glance, to be the tastier option(s).

    The reason the otherwise delectable -pie wasn't suggested was because it wouldn't work.

    The -i takes an optional argument. A rather useful argument at that. If given, perl renames the original file by appending the argument as a suffix to the filename, thereby preserving it if you make any mistakes in your one-liner. Trust me. If you use it, you will eventually find this feature useful. If you fail to use it, you will eventually wonder why you didn't. Out of habit, I would write your one-liner as:

    perl -pi.bak -e 's/text/newtext/g' /path/to/file

    So, anyway, if given -pie perl would is forced to... errrr... eat the 'e' as the backup suffix. Sadly though, "e" isn't usually a very useful suffix.

    -sauoq
    "My two cents aren't worth a dime.";