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.

234 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>BEGIN {# let getopt print a message about# invalid options. we ignore themwhile ((c = getopt(ARGC, ARGV, "lwc")) != -1) {if (c == "l")do_lines = 1else if (c == "w")do_words = 1else if (c == "c")do_chars = 1}for (i = 1; i < Optind; i++)ARGV[i] = ""}# if no options, do allif (! do_lines && ! do_words && ! do_chars)do_lines = do_words = do_chars = 1print_total = (ARGC - i > 2)The beginfile function is simple; it just resets the counts of lines, words, and charactersto zero, and saves the current file name in fname:function beginfile(file){chars = lines = words = 0fname = FILENAME}The endfile function adds the current file’s numbers to the running totals of lines,words, and characters. 2 It then prints out those numbers for the file that was just read. Itrelies on beginfile to reset the numbers for the following data file:function endfile(file){tchars += charstlines += linestwords += wordsif (do_lines)printf "\t%d", linesif (do_words)printf "\t%d", wordsif (do_chars)printf "\t%d", charsprintf "\t%s\n", fname2 wc can’t just use the value of FNR in endfile. If you examine the code in Section 12.3.1 [Noting DataFile Boundaries], page 197, you will see that FNR has already been reset by the time endfile is called.

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

Saved successfully!

Ooh no, something went wrong!