Invictus
Invictus

Reputation: 4338

append new path in variable assignment in multiple scripts

I have an environment variable declared in my perl scripts which are like below. This variable can be slightly different in different perl files. In first file:

$ENV{MY_LIBS} = "$MY_PATH/bin:$HOME/PACKAGE1:$HOME/PACKAGE2";

In Second file:

$ENV{MY_LIBS} = "$MY_PATH/bin:$HOME/MYLIBS1:$HOME/PACKAGE2";

Now say I want to append $MY_PATH/lib to all such files so that they would be like:

In first file:

$ENV{MY_LIBS} = "$MY_PATH/bin:$HOME/PACKAGE1:$HOME/PACKAGE2:$MY_PATH/lib";

In Second file:

$ENV{MY_LIBS} = "$MY_PATH/bin:$HOME/MYLIBS1:$HOME/PACKAGE2:$MY_PATH/lib";

How can I do this with some simple command in Linux ?

Upvotes: 0

Views: 72

Answers (1)

zdim
zdim

Reputation: 66964

You can use a Perl "one-liner" in lieu of a "simple command in Linux"

perl -i.bak -pe's/\$ENV{MY_LIBS}.*\K"\s*;/:$MY_PATH\/lib";/' file1 file2 ...

I assume that $MY_PATH stands for a literal string, otherwise I don't know where it'd come from.

The switches mean:

  • -e signifies that what follows inside '' is evaluated as Perl code, so the program follows

  • -p opens given files and loops over lines so that the code in '' is applied successively to each line; the processed line is printed at the end

  • -i makes it edit input files "in-place" (they're changed) and with .bak backup is kept

Code comments:

The lookbehind-type construct \K drops all previous matches, so nothing is "consumed" out of the string before it; thus the replacement part tacks on the desired string. We do need to put back "; since that was matched after \K and was thus removed from the string (when matched).

Upvotes: 1

Related Questions