Akira
Akira

Reputation: 273

How to find and replace inside a file with some Javascript variable using Bash command

I am writing some code in Javascript, and I have defined couple variables called

const url = "www.google.com"
const data = "xyz"

and I also have a text file, which looks like the following:

clusters:
- cluster:
    server: www.yahoo.com
    certificate-authority-data: abc
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: aws
  name: aws

All I want to do is to replace the "sever" name and "certificate-authority-data" with the variables I defined, which looks like"

clusters:
- cluster:
    server: www.google.com
    certificate-authority-data: xyz
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: aws
  name: aws

I read about to use

sed -i "s%www.yahoo.com%www.google.com%g" "test.txt"

However, here are two issues

  1. I don't really want to refer the "www.yahoo.com" in the terminal, since the url is changed all the time, what I want is to use some regex to capture this url after "server: "

  2. how can I refer the Javascript variable in the terminal?

I am really stuck in here, any helps

Upvotes: 0

Views: 1238

Answers (2)

user7712945
user7712945

Reputation:

if js file is a, text file is b
try gnu sed twice, each for one replace pair ie. 2 lines followed by enter in shell, each is 2 process chained into 1

$ sed -En 's!^.*\burl\s*=\s*"([^"].+)"\s*!s/\\b(server:\\s*).+/\\1\1/i!;te;b;:e p;q' a |sed -i -Ef - b

$ sed -En 's!^.*\bdata\s*=\s*"([^"]+)"\s*!s/\\b(certificate-authority-data:\\s*).+/\\1\1/i!;te;b;:e p;q' a |sed -i -Ef - b

Note: test it first by disusing -i opt at 2nd ie. sed -i -E.. become sed -E...

by one line gnu awk

awk 'FNR==NR {if(/(const\s)?url\s*=/) {u=gensub(/.*url.*"([^"]+)"/,"\\1",1)} else if(/(const\s)?data\s*=/) {v=gensub(/.*data.*"([^"]+)"/,"\\1",1)} next} {if(/server:/) print gensub(/(.*server:\s*).*/,"\\1"u,1); else if (/certificate\S+:/) print gensub(/(.*certificate-authority-data:\s*).*/,"\\1"v,1); else print }' a b

Upvotes: 0

Informagician
Informagician

Reputation: 305

There is a method of getting nodejs to execute a bash command if that is truly desired. NodeJS Shell Commands. In this case, it might look something like this:

const replaceUrl = "www.yahoo.com";
const url = "www.google.com";
const data = "xyz";
child_process.execSync('sed -i "s%' + replaceUrl + '%' + url + '%g" "test.txt"').toString();

I've used the synchronous version here as it is convenient, but the asynchronous version could be used with a callback. The function returns a buffer, so the .toString() is to make sense of any data, but there shouldn't be any coming back in your case.

Upvotes: 1

Related Questions