Igor Wiwi
Igor Wiwi

Reputation: 57

How to use sed or awk for editing really long Java class

I am implementing a Decorator pattern for the class which has a lot of methods. I created this Decorator class and just put all the methods that should be here. Now I have a class with 2000 lines where every part like:

@Override
public String getCapadCode()
{
    return null;
}

should be replaced with:

@Override
public String getCapadCode()
{
    return origin.getCapadCode();
}

Is it possible to somehow automate this process with sed or awk?

Upvotes: 0

Views: 91

Answers (3)

Ed Morton
Ed Morton

Reputation: 203995

Use at your own risk:

$ awk '/^public/{name=$3} /return/{sub(/null/,"origin."name)} 1' file
@Override
public String getCapadCode()
{
    return origin.getCapadCode();
}

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247022

Here's a bit of perl:

perl -pe '
    m{public .* (.+)\(} and $methodName = $1; 
    s{(?<=return )null;}{origin.$methodName();};
' File.java

If you are satisfied it works, call it with perl -i -pe to write-in-place.

Upvotes: 1

chux
chux

Reputation: 701

you can use search and replace with regular expression like this:

search: get(.*)\(\)\R\{\R return null;\R\}

replace: get$1\(\)\R\{\R return origin\.$1;\R\}

I use Eclipse Find/Replace for that.

Upvotes: 1

Related Questions