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

Hi all,

I have two files, abc.txt and xyz.txt. Say in abc.txt, I have a string REPLACE_HERE. And in xyz.txt, I have 2 lines:

hello

world

I want to replace the string "REPLACE_HERE" with "hello" and save it to a file named "hello" (and also repeat this step with the string "world").

Here is my bash script:

#!/bin/bash

while read p; do

        perl -pe 's%REPLACE_HERE%$p%g' abc.txt > $p

done <xyz.txt

I opened "hello" and found out that the text REPLACE_HERE is replaced by nothing. Why is that so?

Replies are listed 'Best First'.
Re: Perl in Bash
by Corion (Patriarch) on Mar 16, 2015 at 12:00 UTC

    Have you looked at the command(s) you are running in bash? set -x will show you what is run. Compare that with what you think should happen. Single quotes do not interpolate in bash.

    Personally, I would write the complete program in Perl instead of keeping the loop in bash.

Re: Perl in Bash
by NetWallah (Canon) on Mar 16, 2015 at 13:09 UTC
    As Corion says, Lack of bash interpolation is the problem.

    to fix, try:

    perl -pe 's%REPLACE_HERE%'$p'%g' abc.txt > $p
    Which gets the $p outside the single quotes. (untested)

            "You're only given one little spark of madness. You mustn't lose it."         - Robin Williams

      Or maybe simpler
      perl -pe "s%REPLACE_HERE%$p%g" abc.txt > $p