100 likes | 291 Views
AWK. Kevin Udink. History of AWK. AWK is initials for the creators Alfred V. Aho Brian W. Kernighan Peter J. Weinberger Started in 1977 Built because they wanted to be lazy?!? Few built-in variables and functions Designed for VERY short programs. Redesigned in 1985 to what we now use
E N D
AWK Kevin Udink
History of AWK • AWK is initials for the creators • Alfred V. Aho • Brian W. Kernighan • Peter J. Weinberger • Started in 1977 • Built because they wanted to be lazy?!? • Few built-in variables and functions • Designed for VERY short programs
Redesigned in 1985 to what we now use • “We being the authors, “knew” how the language was supposed to be used, and so we only wrote one-liners.” • People had expanded the use beyond what it was intended for • Associative arrays were inspired by SNOBOL4 • User defined functions were a compromise • I will explain later
AWK Basics Basics of this pattern matching program pattern { action } For each item that matches the pattern, perform the set actions pattern This will default to printing out each line that matches the pattern { action } This action will be taken on all input
Running a program from the command line: awk [-Fs] ‘program’ optional list of filenames Running a program using a file to hold the program: awk [-Fs] –f progfile optional list of filenames
BEGIN { … } • Contains any initializations that you plan on using during the program • END { … } • Any statements that you would like after the processing of files is completed • function name( parameter-list ) { statement-list } • Loop statements • if, while, for in the sense that is normal • for (variable in array ) { statement-list } • Input and Output • getline • print • system(cmd-line) - used for accessing external programs • close(expression) - used to close a file or pipe
Examples Command Line awk ‘$3 >= 500 { print $1 }’ onyx.passwd AWK File Command line: awk –f usernames onyx.passwd File contents: $3 >= 500 { print $1 } Awk as an Executable awk ‘$3 >=500 { print$1 }’ $* Then you need to run chmod +x on the file that you created
Pros Can Process multiple files in order using a single command Easy to access external programs which extend its capabilities Variables do not need to be declared and initialized Programs are intended to be disposable – quick one liners Easy for automating tasks such as data validation and extraction Cons Slow for large programs and tasks Some syntax gotchas – namely for functions Limited number of builtin functions – most need to be user created Good, Bad, or just plain Simple?