Updating python variable name using Sed in shell script

Question:

I have a py file where we need to update the value of a variable table_name from a shell script using sed. The value will be like $ENV_NAME_ref_table considering we have already exported ENV_NAME as export ENV_NAME='staging'.

What should be the sed command?

I have tried some with sed -i but can’t figure out the regex.

sed -i "s/table_name = ".*"/table_name = "$ENV_NAME_reference"/" /src/utils/abc.py

Asked By: Codistan

||

Answers:

As far as I know, sed is extremely greedy when you use something like .* (although it seems to work in this case). I’d use this regular expression nevertheless:

$ ENV_NAME=staging 
$ sed -i.back -E "s/table_name[[:space:]]*=[[:space:]]*"[^"]+"/table_name = "${ENV_NAME}_reference"/" temp.py
$ tail temp.py.back temp.py
==> temp.py.back <==
table_name="foo"
table_name ="foo"
table_name= "foo"
table_name = "foo"
table_name  =  "foo"

==> temp.py <==
table_name = "staging_reference"
table_name = "staging_reference"
table_name = "staging_reference"
table_name = "staging_reference"
table_name = "staging_reference"

So, table_name followed by optional (*) whitespace ([[:space:]]), followed by =, followed by optional whitespace, followed by ", followed by many things that are not " ([^"]+), finally followed by ".

We need backslaces to escape the doubles quotes because we have to wrap the whole RE in double quotes to interpolate the ENV_NAME variable.

Answered By: IonuČ› G. Stan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.