gawk: Plain Getline
1
1 4.10.1 Using 'getline' with No Arguments
1 ----------------------------------------
1
1 The 'getline' command can be used without arguments to read input from
1 the current input file. All it does in this case is read the next input
1 record and split it up into fields. This is useful if you've finished
1 processing the current record, but want to do some special processing on
1 the next record _right now_. For example:
1
1 # Remove text between /* and */, inclusive
1 {
1 if ((i = index($0, "/*")) != 0) {
1 out = substr($0, 1, i - 1) # leading part of the string
1 rest = substr($0, i + 2) # ... */ ...
1 j = index(rest, "*/") # is */ in trailing part?
1 if (j > 0) {
1 rest = substr(rest, j + 2) # remove comment
1 } else {
1 while (j == 0) {
1 # get more text
1 if (getline <= 0) {
1 print("unexpected EOF or error:", ERRNO) > "/dev/stderr"
1 exit
1 }
1 # build up the line using string concatenation
1 rest = rest $0
1 j = index(rest, "*/") # is */ in trailing part?
1 if (j != 0) {
1 rest = substr(rest, j + 2)
1 break
1 }
1 }
1 }
1 # build up the output line using string concatenation
1 $0 = out rest
1 }
1 print $0
1 }
1
1 This 'awk' program deletes C-style comments ('/* ... */') from the
1 input. It uses a number of features we haven't covered yet, including
1 string concatenation (⇒Concatenation) and the 'index()' and
1 'substr()' built-in functions (⇒String Functions). By replacing
1 the 'print $0' with other statements, you could perform more complicated
1 processing on the decommented input, such as searching for matches of a
1 regular expression. (This program has a subtle problem--it does not
1 work if one comment ends and another begins on the same line.)
1
1 This form of the 'getline' command sets 'NF', 'NR', 'FNR', 'RT', and
1 the value of '$0'.
1
1 NOTE: The new value of '$0' is used to test the patterns of any
1 subsequent rules. The original value of '$0' that triggered the
1 rule that executed 'getline' is lost. By contrast, the 'next'
1 statement reads a new record but immediately begins processing it
11 normally, starting with the first rule in the program. ⇒Next
Statement.
1