How can I use grep to find a string in files, but only search in the first line of these files?
Linux – How to use grep to search only on the first line of files for a specific string
greplinuxsearch
greplinuxsearch
How can I use grep to find a string in files, but only search in the first line of these files?
Best Answer
Two more alternatives :
With
awk
or if your
awk
version doesn't supportnextfile
(thanks to Stéphane Chazelas for the suggestion) :will read only the first line before switching to next file, and print it only if it matches
"pattern"
.Advantages are that one can fine-tune both the field on which to search the pattern for (using e.g.
$2
to search on the second field only) and the output (e.g.$3
to print the third field, orFILENAME
, or even mix).Note that with the
FNR
("current input record number", i.e. line number) version you can fine-tune further the line(s) on which you want to grep :FNR==3
for the third line,FNR<10
for the 10 first lines, etc. (I guess in this case, if you are dealing with very large files and yourawk
version supports it you may want to mixFNR
withnextfile
to improve performances.)With
head
, keeping filenames-v
option ofhead
will print filenames, and option-B1
ofgrep
will print the previous line of matching lines — that is, the filenames. If you only need the filenames you can pipe it further togrep
:As noticed by don_crissti in comments, beware of filenames matching the pattern themselves, though…