Sunday, October 24, 2021

[SOLVED] Grep "-C" command on all machine

Issue

I am using grep -C 1 "matching string" "xty.pom"

This works on Linux machines, but the same code is not working on other platforms like AIX, SunOS_x64, HPUX.

Is there any alternative to this so that same code logic works on all the platforms?


Solution

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.

Improvement

With some minor changes, we can handle overlapping matches better:

awk '/a/{if (NR>1 && !f)print last; f=3} f>1{print} f{f--} {last=$0}'

As an example of output with an overlapping match:

$ printf '%s\n'   a a b |  awk '/a/{if (NR>1 && !f)print last; f=3} f>1{print} f{f--} {last=$0}'
a
a
b

Sun/Solaris

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



Answered By - John1024