3 ms·
When you think about it, this behaviour makes sense. How else would you implement it? I/O is always block oriented. The reason you don't always notice is that U
by xorcist 2y ago
When you think about it, this behaviour makes sense. How else would you implement it? I/O is always block oriented. The reason you don't always notice is that UNIX is so dearly line-based that every layer of the software stack goes to enormous pain to buffer everything to make interactive use convenient. (The article then talks about different types of buffering, but that is not important to the point being made.)
So we are on top of a large pile of optimizations the even make "grep | grep | grep" possible, but we are so spoiled we don't even notice until the pile of abstractions runs too deep and the optimizations doesn't work anymore!
In this specific case, it is however a strange thing to do. Why would you want to start two processes in order to search for two words? Each with its own memory management, scheduling, buffering etc.? Even if the buffering can be turned off, the other overhead will be noticeable.
If you wanted to search for ten words, would you start ten separate grep processes, each responsible for their own word?
No, you would ask grep to search for lines containing these both these two words in any order, like so:
grep 'thing1.*thing2\|thing2.*thing1'
This is probably what the article alludes to in the "grep -E" example (the -E is there in order to not have to escape the pipe character), but the author forgot to write the whole argument so the example is wrong.
It would be practical to have a special syntax for "these things, in any order" in grep, but sadly that's one of the things missing from original grep. This makes it unnecessarily difficult to construct the argument programmatically with a script. This was one of the things Perl solved with lookahead and lookbehind buffers, you can use these to look ahead from the start of the line to see if all words are present:
grep -P '^(?=.*?thing1)(?=.*?thing2)'
This syntax is hard to read and understand, but it's the least bad when needed.
(Related: How to search for any one of several words? That's much easier because each match is independent of each other, just give grep several expressions:
grep -e 'thing1' -e 'thing2'
which has none of the above problems.)