find only the first occurence using only grep

By default grep prints the lines matching a pattern, so if the pattern appears one or more times into a line, grep will print that whole line.

Adding the flag -m 7 will tell grep to print only the first 7 lines where the pattern appears.

So this should do what you want (I haven't tested it):

grep -o -m 1 xyz myfile | head -1

Edit: as pointed out by @Kusalananda, you don't strictly need the -m flag but using it means grep won't need to parse the whole file, and will output the result faster, especially if myfile is a large file.

Tags:

Grep

Patterns