Reputation: 11
I need to delete the comment line in a C program with sed in linux, assuming that each comment line contains the start and end tokens without any other statements before and after.
For example, the code below:
/* a comment line in a C program */
printf("It is /* NOT a comment line */\n");
x = 5; /* This is an assignment, not a comment line */
[TAB][SPACE] /* another empty comment line here */
/* another weird line, but not a comment line */ y = 0;
becomes
printf("It is /* NOT a comment line */\n");
x = 5; /* This is an assignment, not a comment line */
/* another weird line, but not a comment line */ y = 0;
I know that this regex
^\s?\/\*.*\*\/$
matches the lines that I need to delete. However, the following command:
sed -i -e 's/^\s?\/\*.*\*\/$//g' filename
does not do the trick.
I am not too sure what I am doing wrong...
Thanks for your help.
Upvotes: 1
Views: 3782
Reputation: 113994
This does it:
$ sed -e '/^\s*\/\*.*\*\/$/d' file
printf("It is /* NOT a comment line */\n");
x = 5; /* This is an assignment, not a comment line */
/* another weird line, but not a comment line */ y = 0;
Notes:
^\s?
matches zero or one spaces. It looks like you want to match zero or one or more spaces. So, we use instead ^\s*
.
Since you want to delete the lines rather than replace them with empty lines, the command to use is d
for delete.
It is not necessary to delimit a regex with /
. We can use |
, for example:
sed -e '\|^\s*/\*.*\*/$|d' file
This eliminates the need to escape the /
. Depending on how many times /
appears in a regex, this may or may not be simpler and clearer.
Upvotes: 2
Reputation: 204558
This might be what you're looking for:
$ awk '{o=$0; gsub(/\*\//,"\n"); gsub(/\/\*[^\n]*\n/,"")} NF{print o}' file
printf("It is /* NOT a comment line */\n");
x = 5; /* This is an assignment, not a comment line */
/* another weird line, but not a comment line */ y = 0;
/* first comment */ non comment /* second comment */
The above was run on this input file:
$ cat file
/* a comment line in a C program */
printf("It is /* NOT a comment line */\n");
x = 5; /* This is an assignment, not a comment line */
/* another empty comment line here */
/* another weird line, but not a comment line */ y = 0;
/* first comment */ non comment /* second comment */
and uses awk because once you're past a simple s/old/new/ everythings easier (and more efficient, more portable, etc.) with awk. The above will delete any empty lines - if that's a problem then update your sample input/output to include that but it's a easy fix.
Upvotes: 1
Reputation: 3266
What you are doing is replacing your regex with a empty string
sed -i -e 's/^\s?\/\*.*\*\/$//g' filename
that means
sed -i -'s/pattern_to_find/replacement/g' : g means the whole file.
What you need to do is delete the line with the regex
sed -i -e '/^\s?\/\*.*\*\/$/d' filename
Upvotes: 0