How to truncate long matching lines returned by grep or ack

ack, grep, unix

Solution

You could use the grep options `-oE`, possibly in combination with changing your pattern to `".{0,10}<original pattern>.{0,10}"` in order to see some context around it:

       -o, --only-matching
              Show only the part of a matching line that matches PATTERN.

       -E, --extended-regexp
             Interpret pattern as an extended regular expression (i.e., force grep to behave as egrep).

For example (from @Renaud's comment):

grep -oE ".{0,10}mysearchstring.{0,10}" myfile.txt

Alternatively, you could try `-c`:

       -c, --count
              Suppress normal output; instead print a count of matching  lines
              for  each  input  file.  With the -v, --invert-match option (see
              below), count non-matching lines.

Problem

I want to run ack or grep on HTML files that often have very long lines. I don't want to see very long lines that wrap repeatedly. But I do want to see just that portion of a long line that surrounds a string that matches the regular expression. How can I get this using any combination of Unix tools?

Original source

Related problems