简体   繁体   中英

Export Curl information to file using sed

I am trying to get a dns address using curl and I would like to use that dsn address to replace a word in a .js file.

So the .js file contains a word "hostname" and I would like to replace that with the dns address fetched from curl so what I am trying to do is this.

sed 's/hostname/curl -s http://169.254.169.254/latest/meta-data/public-hostname/g' server.js

I get a error message which is sed: -e expression #1, char 26: unknown option to s'

You need to execute the curl command in a subshell first. Then you need to use a different separator because of the '/' in uris. '|' should work

dns_address=$(curl -s http://169.254.169.254/latest/meta-data/public-hostname)
sed "s|hostname|${dns_address}|g" server.js

Notice the double quotes. They're necessary in order to expand the variable.

or if it has to be in one line

sed "s|hostname|$(curl -s http://169.254.169.254/latest/meta-data/public-hostname)|g" server.js

or maybe I misunderstood the question and you want to put the actual command in server.js

sed 's|hostname|curl -s http://169.254.169.254/latest/meta-data/public-hostname|g' server.js

Related: How to use variables in a command in sed?

I just needed to escape the '/' and it works

sed 's/hostname/curl -s http:\/\/169.254.169.254\/latest\/meta-data\/public-hostname/g' server.js

If you want to replace inside the file, you can use a temp file

sed 's/hostname/curl -s http:\/\/169.254.169.254\/latest\/meta-data\/public-hostname/g' server.js > temp.js
mv temp.js server.js

There are better ways to do this, not sure if this meets your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM