假设输入如下:
$ 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}下面两个awk代码片段解析出了我想要的数据:
cat example | awk -v 'RS=\n\n' '/^Col1 /' | awk '$2 == "bar" && $3 > 1 {print $1}'
foo
baz
baz如何将这两个代码片段组合成一个单独的awk代码,例如
awk '
...
...
...
' example发布于 2012-08-29 05:18:12
您可以执行以下操作:
awk '/^Col1 /,/^$/{ if( $2 == "bar" && $3 > 1 ) print $1}' example发布于 2012-08-29 05:11:35
这似乎是可行的。
gawk '/^$/{getline;if(/^Col1/){doit=1}else{doit=0;}} doit && $2=="bar" && $3>1 {print $1}' example分成带注释的可读块,这是:
/^$/ { # 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.
}发布于 2012-08-29 04:51:41
使用一个标志,当发现"Col1“时将其设置为第一列,并在设置后发现空行时将其重置。在此期间,检查最后一个管道的状况:
awk '
$1 == "Col1" {
block = 1;
}
block == 1 && $2 == "bar" && $3 > 1 {
print $1;
}
block == 1 && $0 ~ /^[[:blank:]]*$/ {
exit 0;
}
' infile输出:
foo
baz
bazhttps://stackoverflow.com/questions/12167250
复制相似问题