How to search/replace a directory path in a file using perl

Hello All,

Here is what I am trying to do and maybe you guys can point me in the right direction. I have a file that contains the following string(s):

WARNING: </d1/test/program1> did not find item1
WARNING: </d1/test/program1> item1 does not exist
WARNING: </d1/test/program2> item1 failed to load

WARNING: </d1/test/program1> did not find item2
WARNING: </d1/test/program1> item2 does not exist
WARNING: </d1/test/program2> item2 failed to load

What I am trying to do is search for the string "WARNING: </d1/test/program1> did not find" and replace it with "ERROR: </d1/test/program1> did not find"

Here is what I have so far:

prg_env=test
prg_dir=/d1/$prg_env

perl -pi -e "s/WARNING: \<${prg_dir}\/program1\> did not find/ERROR: \<${prg_dir}\/program1\> did not find/g" filename

Obviously, the above fails because I have / in the directory path. When I change prg_dir as follows to include the escape character \, it works:

prg_dir="\/d1\/$prg_env"

Question: Is there a way around not having to change the $prg_dir as above, and still perform the search and replace using perl? The values for $prg_env and $prg_dir are actually set in another script depending on the environment (i.e. test or prod).

Thanks!

$
$ cat f45
WARNING: </d1/test/program1> did not find item1
WARNING: </d1/test/program1> item1 does not exist
WARNING: </d1/test/program2> item1 failed to load
WARNING: </d1/test/program1> did not find item2
WARNING: </d1/test/program1> item2 does not exist
WARNING: </d1/test/program2> item2 failed to load
$
$
$ prg_env=test
$ prg_dir=/d1/$prg_env
$
$ echo $prg_env
test
$
$ echo $prg_dir
/d1/test
$
$ export prg_env
$ export prg_dir
$
$
$ perl -pi.bak -e "s|WARNING: <${prg_dir}/program1> did not find|ERROR: <${prg_dir}/program1> did not find|g" f45
$
$
$ # Modified file
$ cat f45
ERROR: </d1/test/program1> did not find item1
WARNING: </d1/test/program1> item1 does not exist
WARNING: </d1/test/program2> item1 failed to load
ERROR: </d1/test/program1> did not find item2
WARNING: </d1/test/program1> item2 does not exist
WARNING: </d1/test/program2> item2 failed to load
$
$
$ # Backup file
$ cat f45.bak
WARNING: </d1/test/program1> did not find item1
WARNING: </d1/test/program1> item1 does not exist
WARNING: </d1/test/program2> item1 failed to load
WARNING: </d1/test/program1> did not find item2
WARNING: </d1/test/program1> item2 does not exist
WARNING: </d1/test/program2> item2 failed to load
$
$

tyler_durden

1 Like