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.

230 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>The program begins with a usage function and then a brief outline of the options andtheir meanings in a comment. The BEGIN rule deals with the command-line arguments andoptions. It uses a trick to get getopt to handle options of the form ‘-25’, treating suchan option as the option letter ‘2’ with an argument of ‘5’. If indeed two or more digitsare supplied (Optarg looks like a number), Optarg is concatenated with the option digitand then the result is added to zero to make it into a number. If there is only one digit inthe option, then Optarg is not needed. In this case, Optind must be decremented so thatgetopt processes it next time. This code is admittedly a bit tricky.If no options are supplied, then the default is taken, to print both repeated and nonrepeatedlines. The output file, if provided, is assigned to outputfile. Early on, outputfileis initialized to the standard output, ‘/dev/stdout’:# uniq.awk --- do uniq in awk## Requires getopt and join library functionsfunction usage( e){e = "Usage: uniq [-udc [-n]] [+n] [ in [ out ]]"print e > "/dev/stderr"exit 1}# -c count lines. overrides -d and -u# -d only repeated lines# -u only non-repeated lines# -n skip n fields# +n skip n characters, skip fields firstBEGIN \{count = 1outputfile = "/dev/stdout"opts = "udc0:1:2:3:4:5:6:7:8:9:"while ((c = getopt(ARGC, ARGV, opts)) != -1) {if (c == "u")non_repeated_only++else if (c == "d")repeated_only++else if (c == "c")do_count++else if (index("0123456789", c) != 0) {# getopt requires args to options# this messes us up for things like -5if (Optarg ~ /^[0-9]+$/)fcount = (c Optarg) + 0else {fcount = c + 0

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

Saved successfully!

Ooh no, something went wrong!