tags:

views:

372

answers:

3

To make a long story short, I have a line of text that I'm using grep to see if the letter 'd' exists here is an example of what is going on:

echo d file='hello world' | grep -c -w d
Returns 1, this is correct.

echo file='hello world' | grep -c -w d
Returns 0, this is correct.

echo d file='hello world d' | grep -c -w d
Returns 1, this is correct

echo file='hello world d' | grep -c -w d
Returns 1, this is INCORRECT.

The problem is that I need it to ignore the data inside the single quotes. The last example needs to return 0. I'm more of a C# regex guy and less of a Linux grep guru. Can anyone point me in the right direction. Is grep the right tool to use here or is there something else that might help?

+5  A: 

I'd use sed to remove all text inside quotes, and then do a grep on the output of sed. Something like this:

echo "d 'hi there'" | sed -r "s|'[^']*'||g" | grep -c -w d
Barry Kelly
+2  A: 

Pipe the output through a tool to get rid of anything you don't want, for example sed:

echo d file='hello world' | sed -e "s:'[^']*'::g" | grep -c -w d

This reads: replace (s) anything which matches the regular expression (delimited with :) with the empty string.

Aaron Digulla
+1  A: 

Based on the info you provided, this should work:

grep -c -E "^[^']*?d.*?'.*?'"

%> cat blah.sh

echo d file=\'hello world\' | grep -c -E "^[^']*?d.*?'.*?'"
echo file=\'hello world\' | grep -c -E "^[^']*?d.*?'.*?'"
echo d file=\'hello world d\' | grep -c -E "^[^']*?d.*?'.*?'"
echo file=\'hello world d\' | grep -c -E "^[^']*?d.*?'.*?'"

%> ./blah.sh
1
0
1
0
RC