------------------------- Week 15 Notes for CST8129 ------------------------- -Ian! D. Allen - idallen@idallen.ca *** Keep up on your readings (Course Outline: average 5 hours/week homework) Remember - knowing how to find out an answer is more important than memorizing the answer. Learn to fish! RTFM! (Read The Fine Manual) Announcement: Final Exam Monday Dec 12 3 hours 11h30 - 14h30 ------- Review: ------- Read: 6.13.1 (p. 203) through 6.26.7 (p.278) - OMIT 6.14 redirection and pipes - OMIT 6.15 pipes - OMIT 6.16.6 printf - OMIT 6.16.7 redirection and pipes - OMIT 6.16.8 pipes - OMIT 6.23 user-defined functions - OMIT 6.23 user-defined functions - OMIT 6.25.1 fixed fields (but read use of gsub) - OMIT 6.25.2 multi-line records - OMIT 6.25.3 form letters - OMIT 6.26.2 time functions - OMIT 6.26.4 getline - OMIT 6.26.6 user-defined functions number and string constants - awk doesn't care what's in a variable: awk 'BEGIN { x = "010" ; print x }' awk 'BEGIN { x = "010" ; print x+0 }' passing in command line values: awk '{ print NF, x }' x=4 creating new fields : echo 23 67 | awk ' { $3 = $1 + $2 ; print } ' bult-in variables: NF, NR use of BEGIN and END IF, ELSE, WHILE, break, continue, FOR, next, exit Functions: sub and gsub(regexp, str, [output]) index(str, substr) (starting at one) match(str, regexp) length and length(str) Sample AWK scripts: notes/*awk.txt ---------- This week: ---------- Combining quotes: Text p.987-988 WRONG: awk -F: '$1 == idallen {print $1, $5}' /etc/passwd WRONG: awk -F: '$1 == $idallen {print $1, $5}' /etc/passwd RIGHT: awk -F: '$1 == "idallen" {print $1, $5}' /etc/passwd RIGHT: awk -F: '$1 ~ /^idallen$/ {print $1, $5}' /etc/passwd Remember: awk doesn't care about integers/strings; the shell does In between two single-quoted strings, use a double-quoted string containing a shell variable: 'single quoted'"double quoted"'single quoted' userid="idallen" awk -F: '$1 == "'"$userid"'" {print $1, $5}' /etc/passwd awk -F: '$1 == x {print $1, $5}' x="$userid" /etc/passwd len=8 awk -F: 'length($1) >= '"$len"' {print $1, $5}' /etc/passwd fld=5 awk -F: '{ print $'"$fld"' }' /etc/passwd AWK arrays, associative: for ( i in ARRAY ) { ... } More AWK functions: substr(str, start, [leng]) split(str, ARRAY, [fieldsep]) math functions p.246 truncation: integer(float) rand() range [0,1) and srand(x)