Re: how to use "if" with awk?

Bob Proulx <[email protected]>
Newsgroups gmane.comp.gnu.utils
Message-ID <[email protected]>
Chris wrote:
> I'm trying to use an if query in combination with awk.

I am not an awk syntax expert but AFAIK you don't want to split up the
awk program string into separate arguments.  Quote the entire program
into one string argument.  I think that is the root of your problem.
Your example shows an "if" in program argument one and the rest of the
program in program argument two.

> I'm therefore using this commandline:
> n@test ~]$ gawk if '($8<0.001) {print "SNP:" $2 "  P="$8}' Batch_Call_dev-bs.model.P1.model 

I would do that this way using pattern-action pairs where the pattern
acts as an if statement.  It just seems the most awk-ish way to me.

  gawk '$8<0.001 {print "SNP:" $2 "  P="$8}' Batch_Call_dev-bs.model.P1.model 

I tested with this:

  printf "1 one\n2 two\n3 three\n" | awk '$1<3 {print $0}'
  1 one
  2 two

But using the awk if control syntax in the awk program itself also
works okay.  Here is a test using it:

  printf "1 one\n2 two\n3 three\n" | awk '{ if ($1<3) {print $2;} }'
  one
  two

Hope that helps,
Bob
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.