LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Remove Java code comments (https://www.linuxquestions.org/questions/programming-9/remove-java-code-comments-549319/)

HiOctane21 04-26-2007 06:41 PM

Remove Java code comments
 
Hi,

Can someone suggest a shell script solution to remove Java comments.

I'm able to remove the //.... comments from lines that have no space or text before:

Code:

sed '/^\//d' file.java
But I'm trying to also remove the java comments that are on the same line as the java code and the ones after some tabs or blank spaces.
Also I'd like to remove the comments that are within /*.....*/

Any help is appreciated.

twantrd 04-26-2007 07:22 PM

Here's one for the /* ... */. You should be able to modify it to adjust for //.

Code:

[root@log01 tmp]# cat javacomments
/* this is crap */
/*I hate comments*/

real code goes here
[root@prdlog01 tmp]# cat javacomments | sed 's/\/\*.*\*\///g'



real code goes here
[root@log01 tmp]#

-twantrd

kstan 04-26-2007 07:27 PM

i didn't write the code for you, but ideal (pseudocode )probably like this:

declare linenumberstartcomment=0, linumberstopcomment=0, l=0,begincomment=0;

for i in originalfilecontent.java
if found "/*" in `echo $i`
{ linenumberstartcomment=l
begincomment=1;
}

elseif begincomment = 0 || found "*/" in `echo $i`
begincomment=0;

if begincomment=0
echo $i>> newjava.java

l=l+1
next

...


something like this.

HiOctane21 04-26-2007 07:34 PM

Thanks...

I tried twantrd's solution and it works for /*...*/ comments.
I'll try turning kstan pseudocode into a shell script and will let you know.

ghostdog74 04-26-2007 09:34 PM

if you have Python, here's an alternative:
Code:

#!/usr/bin/python
import re
pat = re.compile('\/\*(.*?)\*\/',re.M|re.DOTALL)
data = open("sourcefile").read()
print pat.sub("",data)

sample input:
Code:

first line /* this is crap */
/*hat comments */ 2nd line /*I hate comments*/
/* comments */
code goes here

output:
Code:

# ./test.py
first line
 2nd line

code goes here


twantrd 04-26-2007 10:06 PM

Quote:

I tried twantrd's solution and it works for /*...*/ comments.
I'll try turning kstan pseudocode into a shell script and will let you know.
What's wrong with modifying mine? Just curious...
-twantrd

kstan 04-27-2007 01:43 AM

I think the comment probably in this pattern

/*Developer: alibaba
*this is the comment
*return int test
*/
public ......


thats why i give another pseudocode.

HiOctane21 04-28-2007 12:45 AM

Kstan...
How would you interpret "if found" in a csh script?

Thanks

HiOctane21 04-28-2007 09:39 AM

People!!!...Look what I found

http://sed.sourceforge.net/grabbag/s.../remccoms3.sed

DamianS 04-28-2007 09:52 AM

Nice find. Should work for php and javascript code as well :cool:


All times are GMT -5. The time now is 08:00 PM.