Say I have this text-file (lorem.txt):
Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna
aliqua.
If I use grep
I can now easily find the row containing eiusmod
by:
$ grep eiusmod lorem.txt
adipiscing elit, sed do eiusmod tempor
By using some sort of context-switch like -C
I can even get the lines surrounding the match:
$ grep -C1 eiusmod lorem.txt
Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna
This is good. But what if I just want to see some of the characters closest to the match on the same line? Not the full line. So a behaviour like this:
$ grep --char-context=3 eiusmod lorem.txt
do eiusmod te
$ grep -n --char-context=5 dol lorem.txt
1:psum dolor si
3:e et dolore m
I could of course do this with some clever sed, awk or other tool:
$ sed -n '/dol/{=;s/.*\(...dol...\).*/\1/p}' lorem.txt | sed 'N;s/\n/:o/'
1:um dolor
3:et dolore
But that is not what I want. It's too complicated and obscure to be usable on a day-to-day basis. So is there a simpler way or tool to achieve this?
This is mainly a problem when doing recursive grep over files with long lines like minified css or other files with long texts without newlines. I first started thinking about this when using git grep
so a solution usable both for plain grep
and git grep
is preferred.
Note also that a grep-pipe-sed
construct is undesirable since that will remove any highlight/colorisation of the match.
grep -o '.\{0,3\}eiusmod.\{0,3\}' lorem.txt
, see thisgrep
demo – Wiktor Stribiżew Aug 29 '19 at 13:08-o
option earlier. Perfect. Its close enough for me. But its not working ongit grep
I think. – UlfR Aug 29 '19 at 13:12grep -o '.\{0,3\}eiusmod.\{0,3\}' | grep --color eiusmod
? – joanis Aug 29 '19 at 13:17git grep -E --all-match '.{0,3}eiusmod.{0,3}' lorem.txt
orgit grep -E --all-match '.{0,3}eiusmod.{0,3}' lorem.txt | grep --color eiusmod
? – Wiktor Stribiżew Sep 16 '19 at 12:17