Srinivas21
Srinivas21

Reputation: 63

sed command finding the lines with only matched pattern

Please suggest me regex using sed which find the lines with only the matched string .

/* a comment line in a C program */
#include <stdio.h>  /* including the libraries */
int main()
{
int n, i, flag = 0; /* assigning the values */

printf("Enter a positive integer: ");
scanf("%d",&n);

for(i=2; i<=n/2; ++i)
{
   /* condition for nonprime number */
    if(n%i==0)
    {
        flag=1;
        break;
    }
}

if (flag==0)
    printf("%d is a prime number.",n);
else
    printf("%d is not a prime number.",n);

return 0; /* returns 0 */
}

In the above text I wanted to delete the only commented lines which are not having any leading or trailing text (OR) I wanted to delete the comments which are not before or after the executable statements.

I have used sed 's_\(/*\)\(.*\)\(*/\)_''_g' input , but it deletes all the comments

Please suggest the appropriate command

Upvotes: 1

Views: 42

Answers (1)

SLePort
SLePort

Reputation: 15461

Try this:

sed '/^[ \t]*\/\*.*\*\/[ \t]*$/d' file

Deletes all commented lines having only potential leading or trailing spaces.

Explanation:

Applies d (delete) command to lines:

  • ^[ \t]*: starting with zero or more spaces or tabs
  • \/\*.*\*\/: followed by comments. /* and */ are escaped here
  • [ \t]*$: ending with zero or more spaces or tabs

Edit:

Removed an extra ^ in the second character range.

Upvotes: 1

Related Questions