0

I am writing a script that runs through an existing c program and finds whether it contains comments:

They should start and end in comment tags:

/* and */ 

How can I achieve this?

Example: This works:

egrep "/\.*\./" sample.txt

But i want to list the lines that start and end with /* / only, for example consider this input: hi / */ hello ; this is not a valid comment but its gonna be in the output when your command is used.

5
  • What are "double" comments? Do you mean something like /* /* foo */ */? Please edit your question and add an example of your input file, indicating what lines you want to match and what lines shouldn't.
    – terdon
    Sep 26 '15 at 16:07
  • @terdon yes i mean that but i would like to know for the simple case of /* */ and i can extend that to double comment
    – KLMM
    Sep 26 '15 at 17:03
  • OK, as I said, please edit your question and include an example.
    – terdon
    Sep 26 '15 at 17:08
  • single line or multi-line ? Sep 26 '15 at 17:16
  • @MichaelDurrant single line
    – KLMM
    Sep 26 '15 at 17:39
1

To find lines containing /* and */, all you need is

grep '/\*.*\*/' file

To find lines that start with /* and end with */, use:

grep '^/\*.*\*/$' file

And to allow whitespace before the start comment and after the end, use:

grep -E '^\s*/\*.*\*/\s*$' file

Since the * is a special character, you need to escape it (\*). Apart from that, everything else is just a regular character. The regex above will match /*, than 0 or more characters (.*) until a */.

3
  • thanks for the answer but i want to list the lines that start and end with /* / only, for example consider this input: hi / */ hello ; this is not a valid comment but its gonna be in the output when your command is used. How do i handle this?
    – KLMM
    Sep 26 '15 at 17:35
  • @KLMM yes, well, that's precisely why I asked you, twice, to edit your question and give us examples.
    – terdon
    Sep 26 '15 at 17:39
  • so sorry will do now
    – KLMM
    Sep 26 '15 at 17:42
0

One approach is to use sed:

sed 's%./*.*/%%; /^$/d'

For example to remove the comments:

printf "hello\nx=1\n/* some comment */\nnot some comment\nthis has /* but no close\n" |
sed 's%.*/\*.*\*/%%; /^$/d'
1
  • thanks for the answer but i want to list the lines that start and end with /* / only, for example consider this input: hi / */ hello ; this is not a valid comment but its gonna be in the output when your command is used. How do i handle this?
    – KLMM
    Sep 26 '15 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.