2

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.)

5
  • 3
    See also To grep 20 characters after and before match Commented Jul 3, 2014 at 19:42
  • @StéphaneChazelas Thanks, it's the same question, but I'm looking for a better answer. ;) Commented Jul 3, 2014 at 19:47
  • 1
    If it is the same question, this kind of clarification might be better if asked in-comments on the original. Commented Jul 3, 2014 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. Commented Jul 3, 2014 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. Commented Jul 3, 2014 at 22:17

1 Answer 1

3

You could do something like:

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.