Reputation: 4690
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:
Returns 1, this is correct:
echo d file='hello world' | grep -c -w d
Returns 0, this is correct:
echo file='hello world' | grep -c -w d
Returns 1, this is correct:
echo d file='hello world d' | grep -c -w d
Returns 1 -- should return 0:
echo file='hello world d' | grep -c -w d
I need it to ignore the data inside the single quotes. Is grep
the right tool to use here or is there something else that might help?
Upvotes: 2
Views: 1311
Reputation: 28207
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
Upvotes: 1
Reputation: 328574
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.
Upvotes: 2
Reputation: 42152
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
Upvotes: 5