abhay kumar abhay kumar - 2 months ago 6x
Linux Question

Grep "-C" command on all machine

I am using grep -C 1 "matching string" "xty.pom" this works on Linux machine,
but the same code is not working on other platforms like,aix,sunos_x64,hpux.
Is there any alternative to this to that same code logic works on all the platforms.


This will function like grep -C 1 "matching string" but should work on platforms that do not support grep's -C option:

awk '/matching string/{print last; f=2} f{print; f--} {last=$0}' File

How it works

  • /matching string/{print last; f=2}

    If the current line matches the regex matching string, then print the previous line (which was saved in last) and set f to 2.

  • f{print; f--}

    If f is nonzero, then print the current line and decrement f.

  • last=$0

    Set last equal to the contents of the current line.


The native awk on Sun/Solaris is notoriously bug-filled. Use instead nawk or better yet /usr/xpg4/bin/awk or /usr/xpg6/bin/awk