4

How can I grep the string which is only in uncommented line? I don't want the result to be included for string in commented line. For example: In file.tx

My name is Jane
#My name is Sara

I want to grep word "name" and print the output, like below: -

My name is Jane

But I don't want the commented line to be display to.

Thanks

3 Answers3

1

Without more details it is not possible to give a perfect answer. You can run something along the lines of:

remove the comments (and maybe literal strings)   | 
grep in the output

Removing comments (multiline or not) can be tricky... We need at least a language specific lexical analyzer to correctly deal with it.

Anyway we can write a quick hack (that is not so robust) Following an example with C comments:

   perl -0pe 's!/\*.*?\*/!!gs' x.c   | grep searchstring
JJoao
  • 12,170
  • 1
  • 23
  • 45
0

Something like this could work (assuming commented lines start with a # sign):

grep -v '^#' myfile.txt | grep string_to_search

You can replace # with any symbol that indicates a comment line (C, c, d, D, * or ! e.g.)

lauhub
  • 962
  • Hi anonymous downvoter, can you explain ? – lauhub Nov 28 '18 at 09:51
  • I did not downvote, but this will print just any line which does not start with #, but OP wants to search a pattern when line is not commented. – pLumo Nov 28 '18 at 10:19
  • @Kusalananda You can replace # with any other character, hence my example and its explanation. And if the comments are multi-lines, grep will not be sufficient and you'll need a dedicated parser. – lauhub Nov 28 '18 at 11:06
  • That should all be part of your answer. – Kusalananda Nov 28 '18 at 11:09
  • Hi, thanks for the solution, but mine doesn't work. I use this in unix – daffodil Nov 29 '18 at 03:05
  • I also use Unix. Which flavor and which shell do you use ? (BSD, Solaris / bash, ksh, etc) – lauhub Nov 29 '18 at 06:47
0

If you want to print the line which is not commented out in a file, then below commands comes handy.

grep -v '^ *#' filename.txt  | grep searchstring

-v -> Inverse
-v "^ *#" -> Print the lines without "#" in the starting line (# ABC - This line is also avoided)

It has worked for me for a very long time & I use this to display the active crontab jobs.

Ruban Savvy
  • 8,659