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.

228 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>13.2.5 Duplicating Output into Multiple FilesThe tee program is known as a “pipe fitting.” tee copies its standard input to its standardoutput and also duplicates it to the files named on the command line. Its usage is as follows:tee [-a] file ...The ‘-a’ option tells tee to append to the named files, instead of truncating them andstarting over.The BEGIN rule first makes a copy of all the command-line arguments into an arraynamed copy. ARGV[0] is not copied, since it is not needed. tee cannot use ARGV directly,since awk attempts to process each file name in ARGV as input data.If the first argument is ‘-a’, then the flag variable append is set to true, and both ARGV[1]and copy[1] are deleted. If ARGC is less than two, then no file names were supplied andtee prints a usage message and exits. Finally, awk is forced to read the standard input bysetting ARGV[1] to "-" and ARGC to two:# tee.awk --- tee in awkBEGIN \{for (i = 1; i < ARGC; i++)copy[i] = ARGV[i]}if (ARGV[1] == "-a") {append = 1delete ARGV[1]delete copy[1]ARGC--}if (ARGC < 2) {print "usage: tee [-a] file ..." > "/dev/stderr"exit 1}ARGV[1] = "-"ARGC = 2The single rule does all the work. Since there is no pattern, it is executed for each lineof input. The body of the rule simply prints the line into each file on the command line,and then to the standard output:{}# moving the if outside the loop makes it run fasterif (append)for (i in copy)print >> copy[i]elsefor (i in copy)print > copy[i]print

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

Saved successfully!

Ooh no, something went wrong!