It was written in man grep:
-o
--only-matching
Print only the matched non-empty parts of matching lines, with each such part on a separate output line. Output lines use the same delimiters as input, and delimiters are null bytes if -z (--null-data) is also used (see [Other Options].
(a link in the manual removed so I could publish this post)
I didn't manage to understand this manual explanation.
Perhaps because English is not my first language.
What is the meaning of "matched non-empty part"?
Is it everything which is not a whitespace character or a tabloid character?
and by the way in my case I match just one line, not "lines".
Thanks
A demo text:
$ printf "%s\n" "hello world" "other stuff" "last line"
hello world
other stuff
last line
A standard grep prints the matchimg line:
$ printf "%s\n" "hello world" "other stuff" "last line" | grep "other"
other stuff
The -o
prints only the matching part:
$ printf "%s\n" "hello world" "other stuff" "last line" | grep -o "other"
other
Here the matching part is just the given word.
The following prints the match of a regular expression:
$ printf "%s\n" "hello world" "other stuff" "last line" | grep -o "[aoui]the"
othe
Two matches in the line:
$ printf "%s\n" "hello world" "other stuff either" "last line" | grep -o "[aoui]the"
othe
ithe
It prints both matches, each on a separate output line.
While by default grep prints a matching line once:
$ printf "%s\n" "hello world" "other stuff either" "last line" | grep "[aoui]the"
other stuff either
I suggest you try out more examples yourself, until you have 100% clarity.
1 Like