in reply to Replacing a string in a file

perl -ne 's!/xxx/yyy/zzz!$ENV{FILE_DIR_PATH}!g' file.txt
(see 3dan's reply)

The character after the s in a search-and-replace doesn't have to be a /. You can put almost anything there and Perl will know to split the arguments to the replace on that character. That way, you won't have to escape the slashes.

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

Note: All code is untested, unless otherwise stated

Replies are listed 'Best First'.
Re: Re: Replacing a string in a file
by edan (Curate) on Sep 04, 2003 at 10:51 UTC

    perl -ne 's!/xxx/yyy/zzz!$ENV{FILE_DIR_PATH}!g' file.txt

    This won't do anything. You are quietly looping over the lines in file.txt, setting $_ in turn, performing the substitution, and going to the next line. If you change the -n option to -p, then at least you are printing the 'new' file to STDOUT, and you could redirect to a file:

    perl -pe 's!/xxx/yyy/zzz!$ENV{FILE_DIR_PATH}!g' file.txt > new_file.txt

    But in truth, Tom_Slick_Adv probably wants the -i switch, which modifies the file in place:

    perl -pi.bak -e's!/xxx/yyy/zzz!$ENV{FILE_DIR_PATH}!g' file.txt

    This will back-up the original file with the extension '.bak'. See perlman:perlrun for more info.

    --
    3dan