I'm using egrep with the -o option in order to just get the matching part of the line, e.g.

cat /usr/share/dict/words | egrep -o '(aa|ii)'

Now I'd like to see some context of the match, i.e. a few characters on the left and on the right. One way to achieve this is by

cat /usr/share/dict/words | egrep -o '.{3}(aa|ii).{2}'

Is there a better (more efficient and elegant) way? (I've gone through the egrep commandline options but didn't find one for this purpose.)

  • 3
  • @StéphaneChazelas Thanks, it's the same question, but I'm looking for a better answer. ;) – Kaarel Jul 3 '14 at 19:47
  • 1
    If it is the same question, this kind of clarification might be better if asked in-comments on the original. – HalosGhost Jul 3 '14 at 19:54
  • 1
    If the Q is a duplicate (it is), the other answers aren't good enough, and you can't find a way to make this a new question, the answer to "Is there a better way?" is No. @HalosGhost Adding a comment to an existing question looking for another answer is unlikely to solicit any response from anyone at all. – goldilocks Jul 3 '14 at 21:37
  • I'd say they're closely related but not duplicates (I answered both). The other one was looking at limiting the (multi-line) context offered by grep -A/B/C and was asking for color, file names and line numbers. This one is simpler as it only asks for context around a (or several) match within a line. – Stéphane Chazelas Jul 3 '14 at 22:17

You could do something like:

$ echo 'aabiicaa' | perl -lne '
   while (/aa|ii/g) {print substr($`,-3)."[$&]".substr($'\'',0,2)}'

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.