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?

  • 1
    Your set of options is a bit odd when complaining about too much information. You want one line after and before your match displayed (-A1 and -B1 resp.), but it's too much? Where exactly do you want your output cropped? – Andreas Wiese Mar 25 '14 at 21:15
  • 1
    Can you give an example input and the output that you are expecting? – Ramesh Mar 25 '14 at 21:19
  • I've altered the command, I test in Ubuntu 13.10, let me know if it works for you. I have a grep option and an egrep option – Eric Mar 26 '14 at 0:08
cat file.txt | grep -o -P '.{0,20}string.{0,20}'

This should do it for you


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
  • 1
    What an ugly test file you have ;) – Ouki Mar 25 '14 at 21:32
  • The rest of the file is actually really useful, that is part of a multi-line comment in the middle of a Scheme that had to be excluded without breaking our parser, it was just a good line to try it with. – Eric Mar 25 '14 at 21:33
  • Since its one of my files, its set to 755, but I can see how cat might not be ideal for an HTML file, you can try passing the file name to grep as a parameter, see my edit. – Eric Mar 25 '14 at 23:42
  • I mean by 777 files that you have 777 copies of different files, not the chown thing. I run $$$ egrep -o '.{0,20}pseudomonas.{0,20}' * $$$. The command stays there infinity and does nothing. This then again seems to work $$$egrep -ori '.{0,20}pseudomonas.{0,20}' *$$$. The same with recursion and case-insetitive. However, it is very slow. I think it should not be that slow. Grep was considerable faster. – Léo Léopold Hertz 준영 Mar 26 '14 at 9:28
  • if catting doesn't work, you can always just put it into a file by adding > results.txt to the end of your command, but it won't tell you which file you found it in. – Eric Mar 26 '14 at 13:44
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.