MZimmerman6
MZimmerman6

Reputation: 8593

Check first N lines of bash file for string

I am trying to write a bash script that can go through and check only the first N lines of a file to match a specific string. I am able to write a simple command that will check the entire file, but information that is contained in lines greater than N may not be accurate.

Here is my current implementation

find . -exec egrep -H -m 1 -l "\<$month/$day/$year\>" {} \;

I was thinking of using the head function to trim the files first but this does not seem to be working. Any suggestions? Thanks in advance

Upvotes: 2

Views: 656

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

This will show you files matching the pattern in the first N lines

find . -type f | xargs egrep -H -m 1 -n "\<$month/$day/$year\>" | awk -F : '$2 <= N { print $1; }'

egrep searches for the first occurrence in a file and adds a line number. awk then searches for all lines with a line number less or equal to N (insert number here) and prints the filename.

Upvotes: 1

Zombo
Zombo

Reputation: 1

Perhaps like this

find -type f | xargs head -N | egrep -H -m 1 -l "\<$month/$day/$year\>"

where N is number of lines.

Upvotes: 0

Related Questions