Use grep -o
that will show you matching parts instead of whole lines. If there are two or more matches in a line then they will be printed on separate output lines.
To see mystring
with neighboring characters, you need to expand the pattern so it matches the neighboring characters as well. The following command will search for (and print) mystring
with up to 10 characters to the left and up to 10 characters to the right:
grep -oE '.{0,10}mystring.{0,10}'
(without -E
you would need .\{0,10\}mystring.\{0,10\}
which does not look that nice).
Notes and quirks:
-o
is not portable, your grep
may or may not support it. GNU grep
does support -o
.
Do not try to match exactly 10 characters. Allowing less is crucial when mystring
occurs near the beginning or near the end of a line. Note .{0,10}
is greedy, so you will get as close to 10 as possible.
Inside mystring 2345 mystring …
the command will find one occurrence of the pattern, not two. You will see mystring 2345 myst
and then the search for the next occurrence will start at ring
, missing one match.
Similarly mystring 234567890foo mystring …
will print mystring 234567890
and the search for the next occurrence will start at foo
. It will find the second mystring
, but it will print foo mystring …
, not 567890foo mystring …
.
If your grep
supports -r
(meaning "read all files under each directory, recursively") then maybe you don't need find
. Example:
grep -rHoE '.{0,10}mystring.{0,10}' ./
find
will be useful if you want to perform additional tests though.
grep -z
would be a good start.