friendlygiraffe
friendlygiraffe

Reputation: 1021

Removing functions from Javascript files using SED

How can I delete, or clear out the unknown contents of a specific function using Bash/SED from a javascript file? For example, my .js file I want to empty func1 and func3 from the following:

function func1(){
    //unknown contents
}
function func2(){
    //unknown contents
}
function func3() {
    func1();
    if (var1) {
        func2();
    } else {
        func4();
    }
}

I want it to look like this

function func1(){
}
function func2(){
    //do something
}
function func3() {
}

if it were HTML blocks it would be easier as each closing tag is unique

Something along the lines of this:

sed -i '' -e 's/function func1(){.*}/function func1(){newcode.*}/g' file.js

Thanks

Upvotes: 1

Views: 426

Answers (2)

ctac_
ctac_

Reputation: 2491

With sed

sed '/function func1\|function func3/!b;:A;N;;/\n}/!{s/\n.*//;bA}' file.js

sed -i to replace.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133610

Following awk may help you in same.

awk '/^}/{flag=""} /function func1/||/function func3/{flag=1;print;next} flag{next} 1'   Input_file

Output will be as follows.

function func1(){
}
function func2(){
    //unknown contents
}
function func3() {
}

Upvotes: 1

Related Questions