tags:

views:

24

answers:

1

Awk is awesome of text manipulation, but a little opaque to me. I would like to run an awk command that boils down to something like this

awk '{$x = ($3 > 0 ? 1 : -1); print $1*$x "\t" $2*$x}' file

I want to assign $x on each line, i.e. not using the -v option, and then use it inside my print statement. Unforunately, after the ; awk has forgotten the values of $1 and $2. And putting the assignment outside the braces doesn't seem to work either. How does this work?

+3  A: 

AWK doesn't use dollar signs on its variables:

awk '{x = ($3 > 0 ? 1 : -1); print $1*x "\t" $2*x}' file

In your version you're assigning a 1 or -1 to $0 (the entire input line) since x==0 (effectively) when the first line of the input file is read. That's why $1 and $2 seem to be "forgotten".

Dennis Williamson
yes, awk is like C, not like Perl
glenn jackman