This question already has an answer here:

How can I grep for a given string in all files in the current directory, and recursively so, only considering the first line? (the #! line, if present, but only if #! is in the -first- line)?

marked as duplicate by Stéphane Chazelas, manatwork, jasonwryan, rahmu, Gilles Feb 28 '13 at 9:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


If you are not forced to use grep:

find . -type f -exec \
  awk 'FNR==1 && /GIVEN_STRING/ { print FILENAME ": " $0; }; FNR>1 {nextfile}' {} +

This causes a lot less CPU load as one process (or very few) does all the work.


Try doing this :

find . -type f -exec head -1 {} \; | grep "GIVEN_STRING"
  • Two processes for every checked file? – Hauke Laging Feb 27 '13 at 23:26
  • one process for every checked file, 2 processes to get everything set up. besides, spawning a head for each file isn't that big a deal. not with today's computers and kernels, anyway. – Bananguin Feb 28 '13 at 7:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.