Aaron Aaron - 3 months ago 12
Linux Question

Piping 2 grep commands into wc

I have a file called a.txt that is 100 lines long.

grep rake a.txt | wc #returns 10 lines

grep -v rake a.txt | WC #returns 90 lines

grep Rake a.txt | wc #returns 3 lines


one of these lines has both, but I want lines with only 'Rake'. I have tried
grep Rake a.txt | grep -v rake a.txt | wc
returns 90 lines?

I want to find all 3 lines with Rake, pipe it into grep, find if any of those 3 lines include Rake but not rake, and then use wc to count the lines that do. I could use redirect to make another file and then grep -v that new file, but that's not really my goal here. I'm sure it's something simple, but how do I fix my command?

Answer

I have tried grep Rake a.txt | grep -v rake a.txt | wc returns 90 lines?

The point of piping is that the output of a command feeds the next one. Instead, you are piping and then saying grep -v rake a.txt, which makes the previous command superfluous.

So you just need to pipe normally:

grep Rake a.txt | grep -v rake   | wc
#                              ^
#                             removed a.txt

You can also use awk and tell it to count lines containing Rake, not rake. Finally, print the counter:

awk '/Rake/ && !/rake/ {count++} END {print count+0}' a.txt