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.

Chapter 13: Practical awk Programs 231}Optind--}} elseusage()}if (ARGV[Optind] ~ /^\+[0-9]+$/) {charcount = substr(ARGV[Optind], 2) + 0Optind++}for (i = 1; i < Optind; i++)ARGV[i] = ""if (repeated_only == 0 && non_repeated_only == 0)repeated_only = non_repeated_only = 1if (ARGC - Optind == 2) {outputfile = ARGV[ARGC - 1]ARGV[ARGC - 1] = ""}The following function, are_equal, compares the current line, $0, to the previous line,last. It handles skipping fields and characters. If no field count and no character countare specified, are_equal simply returns one or zero depending upon the result of a simplestring comparison of last and $0. Otherwise, things get more complicated. If fields haveto be skipped, each line is broken into an array using split (see Section 8.1.3 [String-Manipulation Functions], page 132); the desired fields are then joined back into a line usingjoin. The joined lines are stored in clast and cline. If no fields are skipped, clast andcline are set to last and $0, respectively. Finally, if characters are skipped, substr isused to strip off the leading charcount characters in clast and cline. The two strings arethen compared and are_equal returns the result:function are_equal( n, m, clast, cline, alast, aline){if (fcount == 0 && charcount == 0)return (last == $0)if (fcount > 0) {n = split(last, alast)m = split($0, aline)clast = join(alast, fcount+1, n)cline = join(aline, fcount+1, m)} else {clast = lastcline = $0}

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

Saved successfully!

Ooh no, something went wrong!