Grep first 50 lines of files for pattern

grep

How might one search the first 50 lines of files in a directory for a given string? I'm specifically looking for which database table files (from mysqldump) define a specific field, but I don't want to grep the whole files, which after 20-40 lines of CREATE TABLE continue on to hundreds of INSERT statements.

I could write a Python script to iterate over the first few lines of each file, but from experience Python, though powerful, is slow. I have over 200 *.sql files to go through, and I'd like to learn a solution which I could generalize in the future anyway.

Best Answer

awk (assuming your implementation supports the nextfile statement) can do this quite nicely:

awk 'FNR > 50 { nextfile }; /foobar/ { print FILENAME ": " $0 }' ./*.sql

The first statement skips to the next file once 50 records have been processed. The second statement prints the filename and the matching line for any line containing foobar.

If your awk doesn't have nextfile this variant works too, although I imagine it will be less efficient:

awk 'FNR <= 50 && /foobar/ { print FILENAME ": " $0 }' ./*.sql
Related Question