3 ms·
Well, with a simple haystack like the one used in the example, there really would be no reason not to grep for "silver needle" in the first place. So it's real
by gnosis 14y ago
Well, with a simple haystack like the one used in the example, there really would be no reason not to grep for "silver needle" in the first place. So it's really not the best or most realistic example of the usefulness of the double grep method.
When I use double grep in real life, I often tend to do so on a relatively large haystack, where I don't necessarily know what the second search term will be. In that situation, I'll usually do the first grep, look through its output, and add on the second grep once I see something in the first grep's output that I want to narrow the results down to.
Of course, instead of adding on a second grep, I could modify the original regex (and sometimes I do); but if the original regex is complicated, then modifying it is error prone. And, anyway, using a shell abbreviation, it's very easy to type " G " and have that expand to " | grep " to simply add on another grep, without touching the first regex.
A second, quite common use case for a double grep is when I want the second search term to match whether it's before or after the first term. There's probably some convoluted way to get the same effect using a single regex, but it probably won't be nearly as easy or intuitive as a double grep.