0

I have the next script

cat foo.txt | awk '/ERROR/,/INFO/'

With the input of:

FooFoo
ERROR
Foo1
INFO
FooFoo

Now the result is:

ERROR
Foo1
INFO

I am looking for the next result:

Foo1
INFO

How I can make it work? Thanks for your help

  • 1
    Does this answer your question? [How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?](https://stackoverflow.com/questions/38972736/how-to-print-lines-between-two-patterns-inclusive-or-exclusive-in-sed-awk-or) – Sundeep Jun 25 '20 at 15:39

3 Answers3

2

Give this a try:

awk '/ERROR/,/INFO/' foo.txt | tail -n +2

If your input is from a file, you don't need the cat. just awk '...' file

Kent
  • 189,393
  • 32
  • 233
  • 301
2

Could you please try following, written and tested with shown samples in GNU awk.

awk '
/ERROR/{
  found=1
  next
}
found{
  val=(val?val ORS:"")$0
}
/INFO/{
  print val
  val=count=found=""
}
' Input_file

Explanation: Adding detailed explanation for above.

awk '                         ##Starting awk program from here.
/ERROR/{                      ##Checking if line contains ERROR then do following.
  found=1                     ##Setting found variable here.
  next                        ##next will skip all further statements from here.
}
found{                        ##Checking here if found is SET then do following.
  val=(val?val ORS:"")$0      ##Creating variable val and keep adding value to it in form of current line.
}
/INFO/{                       ##Checking condition if INFO is found in current line then do following.
  print val                   ##Printing val here.
  val=count=""                ##Nullifying val and count here.
}
' Input_file                  ##Mentioning Input_file name here.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

Like this:

awk '
    seen            # a true (1) condition makes awk to print current line
    /ERROR/{seen=1} # if we grep ERROR, assign 1 to seen flag
    /INFO/{seen=0}  # if we grep INFO, assign 0 to seen flag
' file

Output

Foo1
INFO
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223