0

I would like to find files that begin with a particular pattern i.e. the first line of file should contain the pattern, and then print the first 10 lines of such file, is there a way to do that?

Is there a way to tell grep to only search for the first line of file?

2

You would need to scan all files and get the first line, then check for pattern, finally execute a print of the first ten lines. It might get really expensive.

find /path/to/search \
    -type f \
    -exec /bin/bash -c "head -n 1 '{}' | grep 'PATTERN' >/dev/null" \; \
    -exec head -n 10 \{\} \;

The -type f is required to not run head on directories, and grep is redirected since we're only interested in its exit status. The second -exec will only be run on those files that pass the first test.

You'd be well advised to add additional tests before -type f, to reduce the number of files that will be scanned.

0

If awk is an option try this:

find . -type f -exec awk 'NR==1 && /PATTERN/ {x=1} NR>10 {exit} x' {} \;

You can read the following as:

If the first line match PATTERN then set x; if x is set then print the current line (implicit action); in either case exit after the 10th line.

Technically the last condition should be !x || NR>10 to save some CPU cycles, but the original version looks nicer. :)

0

Hope this will be useful.

grep -R -n "PATTERN" *.* | grep ":1:" | cut -d: -f1 | xargs head -n10

This will recursively search for any files including the sub-directories and filter for the first lines and then print first 10 lines for those files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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