1. BEGIN and END PatternBEGIN {
printf ("%-9s %-9s %-9s %-9s\n", "COUNTRY", "AREA", "POPU", "CONTINENT")
printf ("\n")
}
{
print
}
END {
printf ("\nEND.\n")
}
2. Expression PatternBEGIN {
printf ("%-9s %-9s %-9s %-9s\n", "COUNTRY", "AREA", "POPU", "CONTINENT")
printf ("\n")
}
$2 > 1000 && $2 < 4000 {
print
}
END {
printf ("\nEND.\n")
}
The bold part is an expression pattern.
3. String-Matching PatternsAWK provides a notation called
regular expression for specifying and matching strings of characters. Regular expressions are widely used in Unix programs, including its text editors and shell.
A
string-matching pattern tests whether a string contains a substring matched by a regular expression.
The simplest
regular expression is a string of letters and numbers, like
Asia, that matches itself.
A regular expression is not a string-matching pattern. To turn a regular expression into a string-matching pattern, just enclose it in slashes:
/Asia/
This pattern matches when the current input line contains the substring
Asia, either as
Asia by itself or as some part of a large word like
Asian or
Pan-Asiatic, and so on.
Note that
blanks are significant within the string-matching pattern. The string-matching pattern
/ Asia /
matches only when
Asia is surrounded by blanks.
========================================================================
String-Matching Patterns1. /regexpr/
Matches when the current input line contains a substring matched by
regexpr
2. expression ~/regexpr/
Matches if the string value of expression contains a substring matched by
regexpr3. expression !~/regexpr/ Matches if the string value of expression does not contain a substring matched by
regexpr========================================================================
BEGIN {
printf ("%-9s %-9s %-9s %-9s\n", "COUNTRY", "AREA", "POPU", "CONTINENT")
printf ("\n")
}
$5 ~ /America/ {
print
}
END {
printf ("\nEND.\n")
}
The string
$5 ~ /America/
matches the substring of
America in field
$5. and
BEGIN {
printf ("%-9s %-9s %-9s %-9s\n", "COUNTRY", "AREA", "POPU", "CONTINENT")
printf ("\n")
}
$5 !~ /America/ {
print
}
END {
printf ("\nEND.\n")
}
the string
$5 !~ /America/
matches the line whoes field
$5 not include the substring
America.
评论