Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk if else issues

Bash points an arrow to "else" and says "syntax error" in a provocative whining tone.

awk '{if($3 != 0) a = ($3/$4) print $0, a; else if($3==0) print $0, "-" }' file > out 

Why?

like image 241
AWE Avatar asked May 24 '12 14:05

AWE


People also ask

How do I use NF in awk?

NF is a predefined variable whose value is the number of fields in the current record. awk automatically updates the value of NF each time it reads a record. No matter how many fields there are, the last field in a record can be represented by $NF . So, $NF is the same as $7 , which is ' example.

How do I print a specific line in awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.

How do you declare variables in awk?

`awk` command uses '-v' option to define the variable. In this example, the myvar variable is defined in the `awk` command to store the value, “AWK variable” that is printed later. Run the following command from the terminal to check the output.


2 Answers

You forgot braces around the if block, and a semicolon between the statements in the block.

awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out 
like image 113
breiti Avatar answered Nov 03 '22 22:11

breiti


Try the code

awk '{s=($3==0)?"-":$3/$4; print s}' 
like image 39
Jotne Avatar answered Nov 04 '22 00:11

Jotne