Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk - Pass arguments (ARGV) and file to parse in the same command

I am running ubuntu11.10, and I think it uses mawk by default. Suppose I have an awk script named 'script.awk', it receives one argument. Also I want to specify the name of the file I want to parse. So if I would use '10' as an argument to parse 'file', I should run:

./script.awk 10 file

However '10' gets interpreted as a file to parse, and not as the argument. I know I could use the -v flag to set an internal variable, but I would like to use ARGV to be able to check if the argument was passed, like:

if (ARGC < 2) { exit 1 }

Is there a workaround, or I will have to stick the -v flag?

like image 414
KevinRGT Avatar asked Nov 01 '25 01:11

KevinRGT


1 Answers

The BEGIN block in an awk script is executed before the arguments are used. That gives you an opportunity to check for the right number of arguments and make changes. There is a special behavior that if the argument is an empty string, it is skipped over, so you can do this:

  BEGIN {
    if (ARGC<3) exit(1);
    arg=ARGV[1]
    ARGV[1]=""
  }
like image 58
Vaughn Cato Avatar answered Nov 04 '25 04:11

Vaughn Cato