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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With