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 the following data:

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

How to combine two fragments into one awk bit, for example.

 awk ' ... ... ... ' example 
+6
source share
3 answers

You can do:

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

This seems to work.

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

Broken into readable snippets with comments, these are:

 /^$/ { # 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. } 
+5
source

Use the flag, set it when “Col1” was found as the first column, and reset when it found an empty row after setting it. Between this, check the status of your last channel:

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

Conclusion:

 foo baz baz 
+2
source

Source: https://habr.com/ru/post/924003/


All Articles