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.
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.
The answer to your question is in the grep man page:
$grep -m1 'searchstring' file_name
The -m option is the key.-m1 will only show the first match, -m 2 the first 2 occurences and so on.