Karan Kalra Karan Kalra - 1 year ago 55
Bash Question

download zip and replace a variable value in .js file with another value using shell script

I am working on continuous build integrations using jenkins for the first time and i am struck at a point where i need to download a .zip file from a particular url , unzip it, take out the .js files inside it and replace in "my destination folder". Then replace a variable value in one of the .js file with another value

Unzipping, copying and download the .zip file from url in shell script i will be able to handle.
Please help me out on my follwoing query

lets say one of the .js file ( first.js ) has variable

var urlValue = "http://www.ncebpm1295aph01.abc.net"
. I want its value to become
var urlValue = "http://www.ncebpm1217web01.abc.net"

Answer Source

Well, you would want to use wget, most likely, to get the file using a shell script.

wget http://www.ncebpm1295aph01.abc.net

This isn't really a question about JavaScript, since although the file will be formatted to fit JavaScript syntax, you will use a shell interpreter to access and rewrite the file.

I would suggest you try the sed command. The following code is untested:

sed -i 's|http://www.ncebpm1295aph01.abc.net|http://www.ncebpm1217web01.abc.net' yourFile.js

Explanation: this will overwrite the old file (by use of the -i argument) - which is a pretty dangerous operation when experimenting with new commands! I would suggest, for testing purposes, you remove the -i parameter and specify a new file to write to, but I've provided what I think is an answer to the original question.

Limitations: this will only replace the first instance of the matched string on each line inside of the file. It also matches the string exactly, which you may want to put in a variable, etc, to make the script dynamic. Reading up on sed will explain further options - I am also new to shell scripting so I don't know for sure - but I would expect there is a parameter which allows you to exit after the first match.

This would mean you need only ensure that the variable you want to change is at the top of any JS file you operate on.

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