Why does 'grep -q' consume the whole input file?
grep
does stop early, but it buffers its input so your test is too short (and yes, I realise my test is imperfect since it's not seekable):
seq 1 10000 | (grep -q 2; cat)
starts at 6776 on my system. That matches the 32KiB buffer used by default in GNU grep:
seq 1 6775 | wc
outputs
6775 6775 32768
Note that POSIX only mentions performance improvements
When searching several files
That doesn't set any expectations up for performance improvements due to partially reading a single file.
This is obviously due to buffering that grep
does to speed up things. There are tools which are specifically designed to read as many characters as requested and no more. One of them is expect
:
{ expect -c "log_user 0; expect 2"; cat; } < infile
I don't have a system to try this on, but I believe expect
will eat up everything until it encounters the expected string (2
), and then terminate, leaving the rest of the input for cat
.