Let's say I have two pieces of code:
awk ' BEGIN {for (i=0; i<ARGC-1; i++) {printf "ARGV[%d] = %s\n", i, ARGV[i]}} {print "So as you can see, complications can occur."} ' one two three four
This piece won't work unless there's a file called one
in the directory.
awk ' BEGIN {for (i=0; i<ARGC-1; i++) {printf "ARGV[%d] = %s\n", i, ARGV[i]}}' one two three four
This will work normally and one two three four
will be understood as arguments. So why does the former not work? What makes awk think something is from a file and something is argument? Thank you.
After running any BEGIN
blocks, if there is any remaining code, it is run once per line of the input - which means awk
has to read its input. If there is anything in ARGV
when awk
goes to read input, it is interpreted as a list of files to open and read; otherwise, standard input is read instead.
In your example, the print
line that mentions complications is not inside a BEGIN
block, so it won't be run until awk
reads a line of input - which it will try to do from the file one
because that its the first argument.
If you want to pass arguments to your AWK program without having them treated as filenames, you can; just be sure not to leave them in ARGV
if you also have any code outside BEGIN
blocks:
awk 'BEGIN {
for (i=0; i<ARGC-1; i++) {printf "ARGV[%d] = %s\n", i, ARGV[i]};
delete ARGV}
{print "So as you can see, complications can occur."}' one two three four
The above will print out the message and then wait for a line on standard input. Upon receiving any lines, it will print out the message about complications.
If you just want an AWK program to do its thing without trying to read and process any input - leaving aside that AWK is perhaps an odd choice for that scenario - simply put all the code inside one or more BEGIN
blocks. If awk
finishes the BEGIN
blocks and finds no other code, it will exit without attempting to read any input.
awk
needs valid input data (either from file or stdin) to execute code outside BEGIN
block. In first snippet you have a print
statement outside BEGIN
which will be executed if awk
is given some valid input (even if empty). However if your input files don't exist then awk will return this error:
fatal: cannot open file `one' for reading (No such file or directory)
2nd snippet works without valid input because you only have code inside BEGIN
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With