Question: I have to grep through some JSON files in which the line lengths exceed a few thousand characters. **How can I limit grep to display context up to N characters to the left and right of the match?** Any tool other than grep would be fine as well, so long as it available in common Linux packages.

This would be example output, for the **imaginary grep switch Ф**:

```
$ grep -r foo *
hello.txt: Once upon a time a big foo came out of the woods.

$ grep -Ф 10 -r foo *
hello.txt: ime a big foo came of t

```

Answer: 
**Piping stdout to `cut` with the `-b` flag; you can instruct grep's output to only bytes 1 through 400 per line.**

```
grep "foobar" * | cut -b 1-400

```
Taken from: <http://www.topbug.net/blog/2016/08/18/truncate-long-matching-lines-of-grep-a-solution-that-preserves-color/>
and
<https://stackoverflow.com/a/39029954/1150462>

The suggested approach `".{0,10}<original pattern>.{0,10}"` is perfectly good except for that the highlighting color is often messed up. I've created a script with a similar output but the color is also preserved:

```
#!/bin/bash

# Usage:
#   grepl PATTERN [FILE]

# how many characters around the searching keyword should be shown?
context_length=10

# What is the length of the control character for the color before and after the matching string?
# This is mostly determined by the environmental variable GREP_COLORS.
control_length_before=$(($(echo a | grep --color=always a | cut -d a -f '1' | wc -c)-1))
control_length_after=$(($(echo a | grep --color=always a | cut -d a -f '2' | wc -c)-1))

grep -E --color=always "$1" $2 | grep --color=none -oE ".{0,$(($control_length_before + $context_length))}$1.{0,$(($control_length_after + $context_length))}"

```

Assuming the script is saved as `grepl`, then `grepl pattern file_with_long_lines` should display the matching lines but with only 10 characters around the matching string.