21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

222 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>ARGV[1] = "-"ARGC = 2} else if (ARGC - Optind > 1)do_filenames++# if (IGNORECASE)# pattern = tolower(pattern)}The last two lines are commented out, since they are not needed in gawk. They shouldbe uncommented if you have to use another version of awk.The next set of lines should be uncommented if you are not using gawk. This ruletranslates all the characters in the input line into lowercase if the ‘-i’ option is specified. 1The rule is commented out since it is not necessary with gawk:#{# if (IGNORECASE)# $0 = tolower($0)#}The beginfile function is called by the rule in ‘ftrans.awk’ when each new file isprocessed. In this case, it is very simple; all it does is initialize a variable fcount tozero. fcount tracks how many lines in the current file matched the pattern (naming theparameter junk shows we know that beginfile is called with a parameter, but that we’renot interested in its value):function beginfile(junk){fcount = 0}The endfile function is called after each file has been processed. It affects the outputonly when the user wants a count of the number of lines that matched. no_print is trueonly if the exit status is desired. count_only is true if line counts are desired. egreptherefore only prints line counts if printing and counting are enabled. The output formatmust be adjusted depending upon the number of files to process. Finally, fcount is addedto total, so that we know the total number of lines that matched the pattern:function endfile(file){if (! no_print && count_only)if (do_filenames)print file ":" fcountelseprint fcounttotal += fcount}The following rule does most of the work of matching lines. The variable matches istrue if the line matched the pattern. If the user wants lines that did not match, the sense1 It also introduces a subtle bug; if a match happens, we output the translated line, not the original.

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

Saved successfully!

Ooh no, something went wrong!