To grep 20 characters after and before match

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

pcregrep -MnirIso '(?s).{0,20}pseudomonas.{0,20}' . |
  grep --color -e '^' -e pseudomonas

Assumes matches and their context don't overlap and that filenames don't contain pseudomonas.

Also note that the reported line numbers are those of the beginning of the context.

Tags:

Grep

Osx