Anonymous Anonymous - 2 years ago 155
Bash Question

How to use bash to replace specific text from variables in a config file?

I have a config file. E.g.

product_name = "test_product"
table_name = "test_table"

and I have an input file:

DROP TABLE cg_company_activity_{{product_name}};
Select * from {{table_name}}

I want to write a bash script that takes in any input file and search and replaces the variables in the config.cfg and returns the transformed text.


DROP TABLE cg_company_activity_test_product;
Select * from test_table

Any idea on how to do this in a bash script? I know Jinja can do this, but I want to avoid python.

Answer Source
$ awk -F' *= *' 'FNR==NR{gsub(/"/,""); a[$1]=$2;next} {for (k in a)sub("{{" k "}}", a[k])} 1' config.cfg input.sql
DROP TABLE cg_company_activity_test_product; 
Select * from test_table

How it works

  • -F' *= *'

    Tells awk to use optional spaces followed by = followed by optional spaces as the field separator.

  • FNR==NR{gsub(/"/,""); a[$1]=$2;next}

    While reading through the first file, config.cfg, (1) remove all ", (2) assign the second field, $2, as the value for associative array a with key $1, and (3) skip the remaining commands and jump to start over with the next line.

  • for (k in a)sub("{{" k "}}", a[k])

    For every key k in array a, look for {{ k }} in the current line and replace it with the value of the associative array a[k].

  • 1

    This is awk's cryptic shorthand for print-the-line.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download