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.
Find only the first occurence using only grep
greppatterns
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 tellgrep
to print only the first 7 lines where the pattern appears.So this should do what you want (I haven't tested it):
Edit: as pointed out by @Kusalananda, you don't strictly need the
-m
flag but using it meansgrep
won't need to parse the whole file, and will output the result faster, especially ifmyfile
is a large file.