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.
Asked
Active
Viewed 5.8k times
12
dr_
- 28,763
- 21
- 89
- 133
Atchyut Sreekar
- 131
- 1
- 1
- 4
-
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
-
1it 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
2 Answers
18
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.
dr_
- 28,763
- 21
- 89
- 133
-
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. – Apr 12 '17 at 11:54
-
5The `-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<number> option is the key. -m1 will only show the first match, -m2 the first 2 occurrences and so on.
Stephen Kitt
- 411,918
- 54
- 1,065
- 1,164
-
3it wont find the first occurrence it would find the first line with the first occurrence. – Atchyut Sreekar Apr 12 '17 at 12:11
-