Deleting comments from c-file

hii all,
i am writing a shell script to remove comments from a .c/.cpp file.
i have written script as

the above script file deletes line between /* and */ also lines starting with //.

but the problems are :
1) i dont want to delete the content between /** and */.

2)sed -i '/^\//d' $FILE ,this command doesnt delete the single line comment if it starts with space or tab. but i want to delete that also.:wall:

please help me out ..
thnx

try with this .. If satisfied with the o/p, then use the -i option in sed

$ sed 's,/\*\*,,g;s,\*/,,g;s,/\*,,g;s,//,,g' infile.cpp
1 Like

thanx jayan jay !!
but i dont want to delete those single line comments if it comes after some code
eg. :
function(); // calling a function.

i dont want to delete this comment

---------- Post updated at 02:57 PM ---------- Previous update was at 02:27 PM ----------

its also deleting lines with between /** and */

Post some contents of your input file and expected output ..

test.c

expected output:

based on your input file ..

$ sed '/^\/\//d;/^\/\*$/,/^\*\//d' infile.cpp
1 Like

thank you very much !! ..
this script is working. but if there is any tab or space is there before single line comment "//" or /* its not deleting that.
also its not deleting lines between
/* / If it is used in same line i.e. / HELLO */ this line not getting deleted.(i haven't put that case, its my mistake.)
thanks for your kind help !

Try this...

sed  '/\/\*$/,/\*\//d;/\/\*[^*]/,/\*\//d;/\/\*.\*\//d;/^[ \t]*\/\//d' $FILE
1 Like

@siva shankar thank you very much !!

---------- Post updated at 03:24 PM ---------- Previous update was at 01:01 PM ----------

thanks for your reply

but i am still getting a problem e.g.

i am getting output as

but my output should be

please help me

For your above posted input file ..

$ sed '/\/\*$/,/\*\/$/d' infile.cpp
1 Like

@jayan

this command is working fine but its not working for the following case

i need to edit this to make work for above case also !!..

thanks for replying


  1. \t ↩ī¸Ž

sed '/\/\*$/,/\*\/$/d;/\/\*[^*]/,/\*\/$/d;/\/\*.\*\/$/d;/^[ \t]*\/\//d' $FILE

This will work fine unless there is no code like

int main()
{
/*
some code
*/some code or space character
}

Check it...

1 Like

@shiv shankar
thanks for help!!

I hope know its working fine...

1 Like

@shiv shankar
ya its working in same wat as you said
but if the condition like

its deleting some_code2

thanks for helping !!

---------- Post updated 11-09-11 at 10:27 AM ---------- Previous update was 11-08-11 at 06:30 PM ----------

hello every one please help me out !!

for the above scenario alone ..

$ cat infile.cpp
/*
some_code1
*/ some_code2
$
$ sed 's,\*/,\*/\,,g' infile.cpp | tr ',' '\n' | sed '/\/\*$/,/\*\/$/d'
 some_code2
$
1 Like

thanks jayan_jay !!