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

Hi,

New to Perl and just asking a simple question.

I am working in DOS and I have an enviroment variable that is named FILE_DIR_PATH this variable is the name of the path where the files I am looking for is located.

I have a text document that contains a series of directories that come from another system. What I want to do is a find and replace.

Basically I want to find this string /xxx/yyy/zzz in file.txt and replace it with FILE_DIR_PATH.

I know how to open the file however the slashes (/) I am having trouble replacing. What do I need to do in order to remove the directory in file.txt and replace it with FILE_DIR_PATH.

Thank you in advance,

Tom Slick Advanced

Replies are listed 'Best First'.
Re: Replacing a string in a file
by hardburn (Abbot) on Sep 03, 2003 at 16:54 UTC

    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

      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