21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6: Patterns, Actions, and Variables 117⊣ BEGIN {⊣ printf "A=%d, B=%d\n", A, B⊣ for (i = 0; i < ARGC; i++)⊣ printf "\tARGV[%d] = %s\n", i, ARGV[i]⊣ }⊣ END { printf "A=%d, B=%d\n", A, B }$ awk -v A=1 -f showargs.awk B=2 /dev/null⊣ A=1, B=0⊣ ARGV[0] = awk⊣ ARGV[1] = B=2⊣ ARGV[2] = /dev/null⊣ A=1, B=2A program can alter ARGC and the elements of ARGV. Each time awk reaches the end ofan input file, it uses the next element of ARGV as the name of the next input file. By storinga different string there, a program can change which files are read. Use "-" to representthe standard input. Storing additional elements and incrementing ARGC causes additionalfiles to be read.If the value of ARGC is decreased, that eliminates input files from the end of the list. Byrecording the old value of ARGC elsewhere, a program can treat the eliminated argumentsas something other than file names.To eliminate a file from the middle of the list, store the null string ("") into ARGV inplace of the file’s name. As a special feature, awk ignores file names that have been replacedwith the null string. Another option is to use the delete statement to remove elementsfrom ARGV (see Section 7.6 [The delete Statement], page 123).All of these actions are typically done in the BEGIN rule, before actual processing ofthe input begins. See Section 13.2.4 [Splitting a Large File into Pieces], page 226, andsee Section 13.2.5 [Duplicating Output into Multiple Files], page 228, for examples of eachway of removing elements from ARGV. The following fragment processes ARGV in order toexamine, and then remove, command-line options:BEGIN {for (i = 1; i < ARGC; i++) {if (ARGV[i] == "-v")verbose = 1else if (ARGV[i] == "-d")debug = 1else if (ARGV[i] ~ /^-./) {e = sprintf("%s: unrecognized option -- %c",ARGV[0], substr(ARGV[i], 2, 1))print e > "/dev/stderr"} elsebreakdelete ARGV[i]}}To actually get the options into the awk program, end the awk options with ‘--’ andthen supply the awk program’s options, in the following manner:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!