1

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?

phuclv
  • 37,963
  • 15
  • 156
  • 475
abhay kumar
  • 379
  • 1
  • 3
  • 12
  • [edit] your question to show a [mcve] including concise, testable sample input, expected output and what you have tried so far so we can help you. – Ed Morton Aug 18 '16 at 12:21

1 Answers1

3

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

John1024
  • 109,961
  • 14
  • 137
  • 171
  • That awk command will only behave like `grep -C 1` when the regexp doesn't appear at the start of the file or on consecutive lines. Try searching for `a` in a file that contains `a\na\nb\n` (where `\n` is a literal newline) using `grep -C 1` and that awk command and note the grep outputs the file as-is (`a\na\nb\n`) while the awk outputs `\na\na\na\nb\n`. – Ed Morton Aug 18 '16 at 12:18