Can grep show context, but not a full line?

This question is old, but since I stumbled on it while looking for a way to grep only part of a line, here goes:

A workaround is to enable the option 'only-matching' and then to use RegExp's power to grep a bit more than your text:

grep -o ".\{0,50\}WHAT_I_M_SEARCHING.\{0,50\}" ./filepath

Of course, if you use color highlighting, you can always grep again to only color the real match:

grep -o ".\{0,50\}WHAT_I_M_SEARCHING.\{0,50\}"  ./filepath | grep "WHAT_I_M_SEARCHING"

Note:

  • this might not return all expected results if you have several matches per line: the .{0,50} might match part of the following match and thus prevent the matching.
  • This regex is slow. Very slow. (see comments for possible solution)

Bet way I know to display json in a pretty format is using pjson. After the format, your can add your grep command.

$ echo '{"test1":"t1","test2":"t2"}' | pjson
{
   "test1": "t1",
   "test2": "t2"
}

Install it with pip:

pip install pjson

and then, pipe any json content to pjson.