Grep OSX – How to Grep 20 Characters Before and After Match

greposx

I have the problem that I get too much information after the match for

grep -RnisI --color=auto "pseudomonas" *

I want to get only like 20 characters or 10 words after and before the match.

What is the right tool to do such a thing?

Best Answer

cat file.txt | grep -o -P '.{0,20}string.{0,20}'

This should do it for you

Update:

If you don't want to cat, you can just use the grep with the file as a parameter:

grep -o -P '.{0,20}pseudomonas.{0,20}' FileName.html

Also, The -P uses Perl Regex, which the man pages says is experimental, if you want to avoid that flag, you could just use egrep instead:

grep -Eo '.{0,20}yourstring.{0,20}' yourtestfile.txt
Related Question