gawk: Rewind Function
1
1 10.3.2 Rereading the Current File
1 ---------------------------------
1
1 Another request for a new built-in function was for a function that
1 would make it possible to reread the current file. The requesting user
1 didn't want to have to use 'getline' (⇒Getline) inside a loop.
1
1 However, as long as you are not in the 'END' rule, it is quite easy
1 to arrange to immediately close the current input file and then start
1 over with it from the top. For lack of a better name, we'll call the
1 function 'rewind()':
1
1 # rewind.awk --- rewind the current file and start over
1
1 function rewind( i)
1 {
1 # shift remaining arguments up
1 for (i = ARGC; i > ARGIND; i--)
1 ARGV[i] = ARGV[i-1]
1
1 # make sure gawk knows to keep going
1 ARGC++
1
1 # make current file next to get done
1 ARGV[ARGIND+1] = FILENAME
1
1 # do it
1 nextfile
1 }
1
11 The 'rewind()' function relies on the 'ARGIND' variable (⇒
Auto-set), which is specific to 'gawk'. It also relies on the
1 'nextfile' keyword (⇒Nextfile Statement). Because of this, you
1 should not call it from an 'ENDFILE' rule. (This isn't necessary
1 anyway, because 'gawk' goes to the next file as soon as an 'ENDFILE'
1 rule finishes!)
1
1 You need to be careful calling 'rewind()'. You can end up causing
1 infinite recursion if you don't pay attention. Here is an example use:
1
1 $ cat data
1 -| a
1 -| b
1 -| c
1 -| d
1 -| e
1
1 $ cat test.awk
1 -| FNR == 3 && ! rewound {
1 -| rewound = 1
1 -| rewind()
1 -| }
1 -|
1 -| { print FILENAME, FNR, $0 }
1
1 $ gawk -f rewind.awk -f test.awk data
1 -| data 1 a
1 -| data 2 b
1 -| data 1 a
1 -| data 2 b
1 -| data 3 c
1 -| data 4 d
1 -| data 5 e
1