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 253The awk program to process ‘@include’ directives is stored in the shell variable expand_prog. Doing this keeps the shell script readable. The awk program reads through the user’sprogram, one line at a time, using getline (see Section 3.8 [Explicit Input with getline],page 52). The input file names and ‘@include’ statements are managed using a stack. Aseach ‘@include’ is encountered, the current file name is “pushed” onto the stack and the filenamed in the ‘@include’ directive becomes the current file name. As each file is finished,the stack is “popped,” and the previous input file becomes the current input file again. Theprocess is started by making the original file the first one on the stack.The pathto function does the work of finding the full path to a file. It simulates gawk’sbehavior when searching the <strong>AWK</strong>PATH environment variable (see Section 11.4 [The <strong>AWK</strong>PATHEnvironment Variable], page 183). If a file name has a ‘/’ in it, no path search is done.Otherwise, the file name is concatenated with the name of each directory in the path, andan attempt is made to open the generated file name. The only way to test if a file can beread in awk is to go ahead and try to read it with getline; this is what pathto does. 7 Ifthe file can be read, it is closed and the file name is returned:expand_prog=’function pathto(file, i, t, junk){if (index(file, "/") != 0)return file}for (i = 1; i 0) {# found itclose(t)return t}}return ""The main program is contained inside one BEGIN rule. The first thing it does is set upthe pathlist array that pathto uses. After splitting the path on ‘:’, null elements arereplaced with ".", which represents the current directory:BEGIN {path = ENVIRON["<strong>AWK</strong>PATH"]ndirs = split(path, pathlist, ":")for (i = 1; i

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

Saved successfully!

Ooh no, something went wrong!