1

Given a file like

asdasd
123
X
456
X
789
asd
asd
asd
asd

If I run grep: grep -C3 'X' on the above, I get the following results

asdasd
123
X
456
--
456
X
789
asd
asd

It appears that grep only shows the context of each match up to the previous or following match. Is there a way to get it to display the entire context regardless of whether the pattern is contained in it? Looking at man grep, there seems to be no such option. The expected result is as follows:

asdasd
123
X
456
X
789
--
123
X
456
X
789
asd
asd
  • 1
    What version of OSX are you running, and what does grep --version report? The (admittedly very old) Mac I just tried came with GNU grep 2.5.1, which produces something else again (the first 8 lines of the file, with no --). – JigglyNaga Nov 20 '18 at 10:10
  • if you okay with awk, you could adapt the second solution present in https://unix.stackexchange.com/questions/66196/how-to-run-grep-and-show-x-number-of-lines-before-and-after-the-match for your needs – Sundeep Nov 20 '18 at 15:03
  • grep --version reports "grep (BSD grep) 2.5.1-FreeBSD". Running on MacOS Mojave Version 10.14 – kanghj91 Nov 21 '18 at 01:56

1 Answers1

0

Here's a short perl script to do it. It does read the whole file into memory, so might not be appropriate for really big files.

perl -0777 -snE '
    @lines = split /\n/;
    for $idx (grep {$lines[$_] =~ $p} 0...$#lines) {
        say join "\n", @lines[$idx-($n-1) .. $idx+($n-1)], "--";
    }
' -- -n=3 -p='X' file
glenn jackman
  • 85,964