Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep command to skip commented lines

Tags:

linux

I trying to grep for a pattern in a file. I want skip the pattern occurrence if it is commented in that file. For example, there are 2 occurrence of that pattern, but output should be 1 occurrence. Basically it should skip commented lines Can you please suggest a way for this

like image 967
Sanchu Avatar asked Dec 10 '25 17:12

Sanchu


2 Answers

A simple, common way to strip shell comments is:

egrep -v '^\s*#' <file>

Here, egrep is grep with a regular expression pattern as input. The pattern '^\s#' describes lines starting with a '#' letter, or with any amount of whitespace followed by '#'. The option -v inverts the match (non-matching lines get through). You can then pipe to your further pattern search.

Caveat: Comments that appear after code (e.g. echo 'foo' # bar) will not get stripped. You cannot do that with this piping solution.

like image 101
ypnos Avatar answered Dec 13 '25 07:12

ypnos


You could use the option -F in grep. -F stands for fixed strings. For example I have a file that has the below data :

System out of memory
#System out of memory 
System out of memory #1  
1 #System out of memory

Now grep with the -F

 grep -rF "#System out of memory" <path to grep>

Output

./file1:#System out of memory
./file1:1 #System out of memory

This is the basic ideology. Based on your pattern, it has to be modified

like image 38
Arun Kurian Avatar answered Dec 13 '25 09:12

Arun Kurian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!