Взято из: http://www.topbug.net/blog/2016/08/18/truncate-long-matching-lines-of-grep-a-solution-that-preservations-color/ и https://stackoverflow.com/a/39029954/1150462
Предлагаемый подход ". {0,10} . {0,10} "
отлично подходит, за исключением того, что цвет выделения часто искажается. Я создал сценарий с аналогичным выводом, но цвет также сохранился:
#!/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))}"
Предполагая, что сценарий сохранен как grepl
, тогда шаблон grepl file_with_long_lines
должен отображать совпадающие строки, но всего 10 символов вокруг соответствующей строки.