dbrane
dbrane

Reputation: 149

Different results when running awk from command line versus writing awk script using #!/bin/awk -f

I am writing a simple awk script to read a file holding a single number (single line with a single field), subtract a constant and then write the result to another file. This is a warmup exercise to do a more complex problem. So, if the input file has X, then the output file has X-C

When I write the following in the command line, it works:

 awk '{$1 = $1 - 10; print $0}' test.dat > out.dat

The output looks like this (for X = 30 and C = 10):

20

However, I wrote the following awk script :

#!/bin/awk
C=10 
{$1 = $1 - C; print $0}

Next, when I run the awk script using:

./script.awk test.dat > out.dat 

I get an output file with two lines as follows :

X 
X-C

for example, if X=30 and C=10 I get an output file having

30 
20

Why is the result different in both cases? I tried removing "-f" in the shebang but I receive and error when I do this.

Upvotes: 0

Views: 324

Answers (2)

Shelton Liu
Shelton Liu

Reputation: 591

#!/bin/awk C=10 {$1 = $1 - C; print $0}

The awk script you wrote is treated as a separate statement. So you got two lines in the output file.

What you can edit your awk script to ensure the result same as your command line

#!/bin/awk -f
BEGIN { C=10 }
{$1 = $1 - C; print $0}

Upvotes: 0

jhnc
jhnc

Reputation: 16662

This is your awk program:

C=10 
{$1 = $1 - C; print $0}

Recall that awk programs take the form of a list of pattern-action pairs.

Missing action results in the default action being performed (print the input). Missing pattern is considered to return true.

Your program is equivalent to:

C=10 { print $0 }
1 { $1 = $1 -C ; print $0 }

The first pattern C=10 assigns 10 to variable C and because assignments return the value assigned, returns 10. 10 is not false, so the pattern matches, and the default action happens.

The second line has a default pattern that returns true. So the action always happens.

These two pattern-action pairs are invoked for every record that is input. So, with one record input, there will be two copies printed on output.

Upvotes: 4

Related Questions