Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a variable content with another variable content in a file using perl

Tags:

bash

sh

perl

I am writing a shell script to replace a variable content which is an integer with another, using perl in a shell script.

#!/bin/sh

InitialFileStep="$1"
CurrentStage=$((($i*(9*4000))+$InitialFileStep))
PreviousStage=$((($(($(($i-1))*(9*4000)))) + (InitialFileStep)))

perl -pi -e 's/$PreviousStage/$CurrentStage/g' file.txt
echo "Hey!"

It seems it cannot find the variable content in the file. I don't know what is the problem, is it the because the variables are integers and not strings?

like image 679
mnaghd01 Avatar asked Apr 02 '26 03:04

mnaghd01


2 Answers

The shell does not interpret anything inside single quote. '$ThisIsASimpleStringForTheShell' so try:

perl -pi -e 's/'"$PreviousStage"'/'"$CurrentStage"'/g' file.txt

The double quotes prevents possible spaces to mess up your command.

Mixing single and double quotes gives you the possibility to add regex operator to your command, preventing shell to interpret them before perl. This command substitute the contents of $PreviousStage with the contents of $CurrentStage only if the former is alone in a single line:

perl -pi -e 's/^'"$PreviousStage"'$/'"$CurrentStage"'/g' file.txt
like image 94
Giuseppe Ricupero Avatar answered Apr 08 '26 05:04

Giuseppe Ricupero


The variables only exist in your shell script; you can't directly use them in your Perl script.

I hate attempting to generate Perl code from the shell as the previous solutions suggest. That way madness lies (though it works here since you're just dealing with integers). Instead, pass the values as arguments or some other way.

perl -i -pe'BEGIN { $S = shift; $R = shift; } s/\Q$S/$R/g' \
   "$PreviousStage" "$CurrentStage" file.txt

or

export PreviousStage
export CurrentStage
perl -i -pe's/\Q$ENV{PreviousStage}/$ENV{CurrentStage}/g' file.txt

or

S="$PreviousStage" R="$CurrentStage" perl -i -pe's/\Q$ENV{S}/$ENV{R}/g' file.txt
like image 41
ikegami Avatar answered Apr 08 '26 04:04

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!