1

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.

  • Do you have many lines in your file? Do you want to find the first word in whole file or the first word in each line? – Arkadiusz Drabczyk Apr 12 '17 at 11:54
  • 1
    it looks like you're asking people to provide you the full command.That's not really how unix.stackexchange works. You should show what you've done, and where you're stuck – Modassir Haider Apr 12 '17 at 12:02
6

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.

  • Okay. If I assume there is only one such word per line, grep -o -m 1 "exp" filename would do my job right? – Atchyut Sreekar Apr 12 '17 at 11:40
  • 2
    @AtchyutSreekar No, that would'nt, it would fetch all the matching patterns from te first line. You need to pipe that to head -1 to get the real first. – user218374 Apr 12 '17 at 11:54
  • 2
    The -m 1 is not needed. The matches returned by -o will be on separate lines and head -1 will pick the first match. Removing -m 1 will make grep go through the entire file (or stop when it notices that it can't write to stdout any longer because head has exited), but it make it portable to other Unices that don't have the -m flag (BSD). – Kusalananda Apr 12 '17 at 12:22
-1

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.

  • 1
    it wont find the first occurrence it would find the first line with the first occurrence. – Atchyut Sreekar Apr 12 '17 at 12:11
  • yes indeed you do have right. – Med Saleh Mdini Apr 12 '17 at 12:12

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.