130 likes | 202 Views
Lecture 21: Perl Programming ( ch 11). IT244 - Introduction to Linux / Unix Instructor: Bo Sheng. Regular Expressions. =~, !~ /regular expression/ “aged”=~/ ge / perl -e ‘if (“aged”=~/ ge /) {print “true<br>”;}’ “aged”!~/ xy / “aged”=~/a..d/ “/ usr /doc”=~// usr / Table 11-3.
E N D
Lecture 21: Perl Programming (ch 11) IT244 - Introduction to Linux / Unix Instructor: Bo Sheng
Regular Expressions • =~, !~ • /regular expression/ • “aged”=~/ge/ • perl -e ‘if (“aged”=~/ge/) {print “true\n”;}’ • “aged”!~/xy/ • “aged”=~/a..d/ • “/usr/doc”=~/\/usr/ • Table 11-3
Regular Expressions • Special characters • .: single character • \d: single digit • \D: single non-digit • *: any number of occurrences (.*) • +: at least one occurrences • Replace strings • $str=~ s/search-string/replace-string/ • ~it244/it244/lec21/re10a.pl
Regular Expressions • Matching patterns • Greedy matching (by default) • Non-greedy matching • ~it244/it244/lec21/re_match.pl • Bracket • $str=~ s/abc(.*)def/…/ • Assign the selected string to variables $1, $2, … • ~it244/it244/lec21/bracket.pl
Misc • Get shell variable • $ENV{“varname”} • ~it244/it244/lec21/shell_var.pl • Open a directory • opendir $dir, directory_name • readdir $dir • ~it244/it244/lec21/dirs.pl
AWK (ch 12) IT244 - Introduction to Linux / Unix Instructor: Bo Sheng
Introduction • What is AWK? • Pattern processing language • Data driven, filter, report writer • Alfred Aho, Peter Weinberger, Brian Kernighan • awk, nawk (new awk): from AT&T • gawk (GNU awk)
Introduction • Usage pattern { action } • awk ‘/chevy/ {print}’ cars • ‘’ is recommended BEGIN { } END { } • ~it244/it244/lec21/simple • awk –f simple cars
Patterns • Missing pattern • gawk ‘{print}’ cars • Missing action • gawk ‘/chevy/’ cars • Fields • gawk ‘{print $3, $1}’ cars
Patterns • Contains (~) • gawk ‘/h/’ cars • gawk ‘$1 ~ /h/’ cars • Match at the beginning(^)/end($) • gawk ‘$1 ~ /^h/’ cars • gawk ‘$3 ~ /5$/’ cars
Patterns • Comparison • gawk ‘$3 == 1985’ cars • gawk ‘$5 <= 3000’ cars • gawk ‘$5 > “2000”’ cars • gawk ‘$5 > 2000 && $5<6000’ cars • Range (,) • gawk ‘/volvo/, /bmw/’ cars • gawk ‘/chevy/, /ford/’ cars
Special Variables/Functions • $1~$n, $0 (value of the current line) • length function (number of characters) • gawk ‘{print length, $0}’ cars • NR (number of record) • gawk ‘length>24 {print NR}’ cars • gawk ‘NR==2, NR==5’ cars • FS (field separator) / OFS (output) • ~it244/it244/lec21/fs • gawk –f fs /etc/passwd
Examples • Find the maximum number • ~it244/it244/lec21/max • gawk -f max cars • Calculate average values • ~it244/it244/lec21/summary • gawk -f summary cars