AWK - no search results

Hi all,

I'm new to awk and I'm experiencing syntax error that I don't know how to resolve. Hopefully some experts in this forum can help me out.

I created an awk file that look like this:

$ cat myawk.awk
BEGIN {
VAR1=PATTERN1
VAR2=PATTERN2
}

/VAR1/ { flag=1 }
/VAR2/ { flag=0 }
{ if (flag == 1) { print $0 } }

The purpose of this awk file is to accept 2 patterns from the command line and extract sections that is between these 2 patterns. And I'm using this file to search for sections that in between [W] and [i], also [E] and [i]. Therefore, in command line, I set

PATTERN1="^\[.\]" and PATTERN2="^\[I\\]" :

$ gawk -v PATTERN1="^\[.\]" -v PATTERN2="^\[W\]" -f myawk.awk < myfile.txt

and I'm not getting any output. However, if I change the awk file to the following:

$ cat myawk_no_input.awk
BEGIN {
^\[.\]=PATTERN1
^\[I\\]=PATTERN2
}

/^\[.\]/ { flag=1 }
/^\[I\\]/ { flag=0 }
{ if (flag == 1) { print $0 } }

I'll get what I needed. Can anyone please explain to me what have I done wrong in the first version of myawk.awk?

Thanks!

Try this:

$0 ~ VAR1 { flag=1 }
$0 ~ VAR2 { flag=0 }
{ if (flag == 1) { print $0 } } 

instead of:

/VAR1/ { flag=1 }
/VAR2/ { flag=0 }
{ if (flag == 1) { print $0 } } 

The BEGIN section isn't necessary.

Regards

Thanks for reply, Franklin.

I tried, it doesn't work. I don't think I tried $1 instead of $0 because each lines is a big long sentence.

Any other thoughts?

Thanks!

It should be easier if you post a part of the file and the patterns you're searching for.

Regards

I just attach the text file to this thread (for readability).

What I would like to do is extract all the information for warnings ([W]) and errors ([E]).

Thanks again.

It should work if you define the patterns as follow:

gawk -v PATTERN1="^\[E\]" -v PATTERN2="^\[W\]" -f myawk.awk < myfile.txt

myawk.awk should looks like:

$0 ~ PATTERN1 || $0 ~ PATTERN2 { print }

Regards

I tried what you suggested and here are the errors I received:

gawk: warning: escape sequence `\[' treated as plain `['
gawk: warning: escape sequence `\]' treated as plain `]'
gawk: getpara.awk:1: each rule must have a pattern or an action part

Also, I think by doing

$0 ~ PATTERN1 || $0 ~ PATTERN2 { print }

it will only print out the line with [W] & [E] labels and ignore and information following the lines.

Try this oneliner:

awk '$0 ~ /^\[W\]/ || $0 ~ /^\[E\]/ { print }' myfile.txt

Regards