0

As Unix does not offer -A or -B options with grep, I am looking for the way to achieve the same result in Unix. The purpose is to print all the lines not starting with a specific pattern and the preceding line.

grep -B1 -v '^This' Filename

This will print all the lines not starting with the string 'This' and the preceding line. Unfortunately my script needs to be run on Unix. Any workaround will be great.

mklement0
  • 245,023
  • 45
  • 419
  • 492
instinct246
  • 810
  • 8
  • 12
  • 1
    What do you mean by _Unix_? Do you mean you can only assume [`grep` features defined by _POSIX_](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html)? – mklement0 Jun 18 '16 at 16:04
  • Could you specify your flavour of *Unix*? [This answer+comment](http://stackoverflow.com/a/9083/668501) suggest that GNU utils are posix compliant, but others unix implementations are not Posix compliant, but differes from vendor to vendor – Soren Jun 18 '16 at 16:10
  • 2
    @Soren, what does GNU grep's conformance with POSIX have to do with it? Its `-A` and `-B` options are not part of POSIX, which seems to be the point of the question. – John Bollinger Jun 18 '16 at 16:20

1 Answers1

6

You can use awk:

awk '/pattern/{if(NR>1){print previous};print}{previous=$0}'

Explanation:

# If the pattern is found
/pattern/ {
    # Print the previous line. The previous line is only set if the current
    # line is not the first line.
    if (NR>1) {
        print previous
    }
    # Print the current line
    print
}
# This block will get executed on every line
{
    # Backup the current line for the case that the next line matches
    previous=$0
}
hek2mgl
  • 133,888
  • 21
  • 210
  • 235
  • @ hek2mgl : Your suggestion seems to be useful. Thanks. But the bracketing in the command may need a review. Could you please check and correct as needed. – instinct246 Jun 19 '16 at 07:40
  • I'm sorry, that was a typo. changed it – hek2mgl Jun 19 '16 at 07:45
  • Excellent! This works. I understand 'NR>1' part.Would you help me understand the meaning of - {print last};print}{last=$0} . – instinct246 Jun 19 '16 at 14:31
  • Pretty comprehensive! I was thinking awk only filters out the specific lines matching with the pattern specified in the beginning. But it does not seem so. "# This block will get executed on every line" - Assuming this to be each and every line of the file, I have my confusion resolved now. Thanks much! Not sure, If should ask/post in a different thread - But I am sure you can help me with this. What would be the command to find all the lines not starting with a specific pattern and then appending it to the previous line. – instinct246 Jun 19 '16 at 16:07