Refrence Shell variable in Perl code.

:confused:

I have 2 files a & b
Contents of a are:-

This is a Good Boy
This is a Good Boy
This is a Very Good Boy
This is a Good Boy
This is a Good Boy

The contents of b are

This is Testing Beta

I have a piece of code :-

i=`cat a|grep "Very Good"`
echo $i
perl -pi -e 's/^(This is a Very Good Boy)/$1."\n".`cat b`/e' a

Now the above piece of code works perfectly well. That is String 'This is Testing Beta', needs to be added just under the string ''This is a Very Good Boy', followed by the remaining lines of code from file a. However, I want to refrence Shell variable 'i' instead of hard coding the string 'This is a Very Good Boy'? Please help urgent.

Any other forms of help are also welcome, I mean if we could do the above effort with just Shell,awk,sed or combination of all 3. All your help is highly appreciated.

Regards
Sri
:slight_smile:

The Final Output Should look something like this. I mean the final contents of File a
----------------------
This is a Good Boy
This is a Good Boy
This is a Very Good Boy
This is Testing Beta

This is a Good Boy
This is a Good Boy
-------------------------

Something like that:

perl -pi -e 's/^($ENV{i})/$1."\n".`cat b`/e' a

Or:

myVar="This is a Very Good Boy"

sed '/'$myVar'/r b' a

Regards

Something is going on with the way this forum is presented to my PC and it is no longer so easy to find a way to reply...

But you have the answer in one of the other replies already...

the %ENV hash (built into perl) holds all environment vars. Inside your perl script you can use $ENV{i} and that will be the value of the shell variable 'i'

Hi Buddy,

Thanks for the quick reply. But this is not working the way I want. The output using the above piece is

This is Testing Beta
This is a Good Boy
This is Testing Beta
This is a Good Boy
This is Testing Beta
This is a Very Good Boy
This is Testing Beta
This is a Good Boy
This is Testing Beta
This is a Good Boy

Please note that the variable i is a Shell variable, which has the output of Unix Command.
i=`cat a|grep "Very Good"`

Please help buddy its a emergency.

This is definitely not encouraged in the forum. Please :slight_smile:

Here is one more,

awk -v var=$i 'BEGIN { while (getline < "second_file") arr[i++]=$0 } { if(match($0, var)) { for (j=0; j<i ;j++) { printf "%s\n%s\n\n", var, arr[j] }; next } print }' first_file