user145664
user145664

Reputation: 63

combine multiple awk commands

Assuming the following input:

$ cat example
{many lines of text}

Col1 Col2  Col3
foo  bar   2 
bar  baz   3
baz  bar   8
bar  foo   0
foo  baz   9
baz  bar   3

{many more lines of text}

The following two awk snippets parse out the data I'm after:

cat example | awk -v 'RS=\n\n' '/^Col1 /' | awk '$2 == "bar" && $3 > 1 {print $1}'
foo
baz
baz

How do I combine the two snippets into a single bit of awk, e.g.

awk '
...
...
...
' example

Upvotes: 6

Views: 13037

Answers (3)

William Pursell
William Pursell

Reputation: 212158

You can do:

awk '/^Col1 /,/^$/{ if( $2 == "bar" && $3 > 1 ) print $1}' example

Upvotes: 6

ghoti
ghoti

Reputation: 46816

This seems to work.

gawk '/^$/{getline;if(/^Col1/){doit=1}else{doit=0;}} doit && $2=="bar" && $3>1 {print $1}' example

Broken into readable chunks with comments, this is:

/^$/ {                      # Look for a blank line
  getline;                  # Get the next line
  if (/^Col1/) {            # See if your column heads exist.
    doit=1                  # If they do, set a boolean to true
  } else {
    doit=0;                 # Otherwise, false.
  }
}

doit && $2=="bar" && $3>1 { # Check the boolean AND your conditions, then
  print $1                  # print.
}

Upvotes: 5

Birei
Birei

Reputation: 36252

Use a flag, set it when found "Col1" as first column and reset it when found a blank line after setting it. Between that, check for the condition of your last pipe:

awk '
    $1 == "Col1" { 
        block = 1; 
    } 
    block == 1 && $2 == "bar" && $3 > 1 { 
        print $1; 
    } 
    block == 1 && $0 ~ /^[[:blank:]]*$/ { 
        exit 0; 
    }
' infile

Output:

foo
baz
baz

Upvotes: 2

Related Questions