Find only the first occurence using only grep

greppatterns

Suppose i have a file with many words, i want to find only the first word with the pattern "xyz". How do I do it if there are multiple words with this pattern on the same line?
-m returns all the words in the first line in which it matches. I need only grep command.

Best Answer

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.

Related Question