grep second time faster
The second time should be already faster (if
grep is I/O bound) as the file should be in the cache of the operating system.
grep doesn't save any state at all and only works with the provided input parameter there is no way to to reuse previous results with
If you regularly have this problem you may want to look into desktop search engines or text indexing to improve search time as well as results.
If the files are still in the disk cache, the second search will be faster.
If you want to speed up searches, you need to build an index. This is well beyond grep's job: it's a search tool, not an indexing tool. Command-line-friendly full-text indexing? lists some indexing tools.
There are ways in which you can leverage grep to make repeated searches faster. For example, first obtain the list of matching files with
grep -l. If your file names don't contain any whitespace or shell wildcards
*?\[, you can stuff the file names in a variable:
f=$(grep -l -r foo .) grep foo $f grep -C3 foo $f grep foobar $f