amithgc
amithgc

Reputation: 6265

Shell script to find and delete a text pattern from .java files

Can anyone help me with a shell script which can do the following?

I want to delete catch block from java files. I need a shell script that can search the catch block and delete it.

I have hundreds of java files which have the following catch block, and they need to be deleted by shell script:

} catch (SomeException e) {
if (Loging.isOn()) {
    System.out.println("Exception");
    // and also some code which differs from file to file.
}

Upvotes: 1

Views: 568

Answers (1)

Steve LeBlanc
Steve LeBlanc

Reputation: 26

I am on Windows and have no Linux machine handy. I assume you are on a Linux system. What you need is this sed command, available in BASH on Linux. I have not been able to verify this code, but it should work as written, perhaps with a tweak. This assumes the blocks you want deleted begin with "} catch" and ends with a "}", with no other right curly braces inside that block. Of course, you need to be in the proper directory when you run this code, so use the CD command to get there. If the ” in …” is excluded, the loop will run as if “in $@” was given.

for i in /directory/*.java
do
   # echo 'Working on $i file'
   copy $i tempfil.txt
   sed   -e '/\} catch/,/^\}/d' tempfil.txt > $i
done

Upvotes: 1

Related Questions