Chris
Chris

Reputation: 193

AWK script returns 0 records

If I execute

echo "abcd" | awk '{print NR}'

returns 1, which is good.

But if I create a script file script.awk with the content:

BEGIN{print NR}

and execute

echo "abcd" | awk -f script.awk

returns 0.

Why?

Upvotes: 0

Views: 283

Answers (2)

hek2mgl
hek2mgl

Reputation: 158130

awk programs follow this scheme:

CONDITION { ACTION(S) } NEXT_CONDITION { ACTION(s) }

You can omit ACTION(S). In that case awk will simply print the current record.

BEGIN is just a special condition which is true before awk starts to read the input. FYI, there is also an END condition which is true after awk has been processed all lines of input.

There is no difference in they syntax of commanline scripts and scripts put into a file.


Conclusion:

You can simply put this into your script:

test.awk

{print NR}

and call it like:

awk -f test.awk <<< 'hello'

Upvotes: 0

fedorqui
fedorqui

Reputation: 290165

You are checking the number of records in the BEGIN block and this is not going to work.

Why? Because when in the BEGIN block, the file is not loaded yet, neither the standard input.

Instead, print it in the END block.

$ cat a.wk                 
END {print NR}
$ echo "abcd" | awk -f a.wk
1

From man awk:

Gawk executes AWK programs in the following order. First, all variable assignments specified via the -v option are performed. Next, gawk compiles the program into an internal form. Then, gawk executes the code in the BEGIN rule(s) (if any), and then proceeds to read each file named in the ARGV array (up to ARGV[ARGC]). If there are no files named on the command line, gawk reads the standard input.

Upvotes: 2

Related Questions