soheshdoshi
soheshdoshi

Reputation: 624

Replace Environment variable with bash

export const environment = {
  production: true,
  firebase: {
    apiKey: "APIKEY",
    authDomain: "AUTHDOMAIN",
    databaseURL: "DATABASEURL",
    projectId: "PROJECTID",
    storageBucket: "STORAGEBUCKET",
    messagingSenderId: "MESSAGINGSENDERID"
  },
  functionURL:"FUNCTIONSURL",

};

I have this type of file now I want to replace all variables (APIKEY, AUTHDOMAIN,..) using bash, please provide some generic solution!

sed  -i 's/($APIKEY)/('"$Master_APIKEY"')/g'

Already use for every variable in file.

Upvotes: 0

Views: 358

Answers (2)

builder-7000
builder-7000

Reputation: 7627

To prepend every variable with the string $Master_ use:

sed 's/\(.*: "\)\(.*\)"/\1$Master_\2"/g' inputfile

this command works like this:

  • \(.*: "\): match everything until the string : " and capture in group 1

  • \(.*\)": match everything before the last " and capture in group 2

  • \1$Master_\2": replace with contents of group 1, followed by $Master_ and contents of group 2.

output:

export const environment = {                                                
  production: true,                                                         
  firebase: {                                                               
    apiKey: "$Master_APIKEY",                                               
    authDomain: "$Master_AUTHDOMAIN",                                       
    databaseURL: "$Master_DATABASEURL",                                     
    projectId: "$Master_PROJECTID",                                         
    storageBucket: "$Master_STORAGEBUCKET",                                 
    messagingSenderId: "$Master_MESSAGINGSENDERID"                          
  },                                                                        
  functionURL:"FUNCTIONSURL",                                               

};

you can include the -i.bak flag to replace the original file and make a backup file.

Upvotes: 2

Inder
Inder

Reputation: 3816

Here is an example for what you are trying to acheive:

P.S. you don't need to cat and all, you can directly use sed -i on the file, this is just to demonstrate a single line code where we are inserting a variable on the given pattern:

a=REPLACEMENT ;cat inputfile | sed "s/\"\(.*\)\"/\""$a"_\1\"/g"

the output from the input file provided by you :

export const environment = {
  production: true,
  firebase: {
    apiKey: "REPLACEMENT_APIKEY",
    authDomain: "REPLACEMENT_AUTHDOMAIN",
    databaseURL: "REPLACEMENT_DATABASEURL",
    projectId: "REPLACEMENT_PROJECTID",
    storageBucket: "REPLACEMENT_STORAGEBUCKET",
    messagingSenderId: "REPLACEMENT_MESSAGINGSENDERID"
  },
  functionURL:"REPLACEMENT_FUNCTIONSURL",

};

Upvotes: 2

Related Questions