Download Bash Guide for Beginners
Transcript
Bash Guide for Beginners
Quotes, dollar signs and other meta−characters should be escaped with a backslash.
6.2.3. The print command and regular expressions
A regular expression can be used as a pattern by enclosing it in slashes. The regular expression is then tested
against the entire text of each record. The syntax is as follows:
awk 'EXPRESSION { PROGRAM }' file(s)
The following example displays only local disk device information, networked file systems are not shown:
kelly is in ~> df −h | awk '/dev\/hd/ { print $6 "\t: " $5 }'
/
: 46%
/boot
: 10%
/opt
: 84%
/usr
: 97%
/var
: 73%
/.vol1 : 8%
kelly is in ~>
Slashes need to be escaped, because they have a special meaning to the awk program.
Below another example where we search the /etc directory for files ending in ".conf" and starting with
either "a" or "x", using extended regular expressions:
kelly is in /etc> ls −l | awk '/\<(a|x).*\.conf$/ { print $9 }'
amd.conf
antivir.conf
xcdroast.conf
xinetd.conf
kelly is in /etc>
This example illustrates the special meaning of the dot in regular expressions: the first one indicates that we
want to search for any character after the first search string, the second is escaped because it is part of a string
to find (the end of the file name).
6.2.4. Special patterns
In order to precede output with comments, use the BEGIN statement:
kelly is in /etc> ls −l | \
awk 'BEGIN { print "Files found:\n" } /\<[a|x].*\.conf$/ { print $9 }'
Files found:
amd.conf
antivir.conf
xcdroast.conf
xinetd.conf
kelly is in /etc>
The END statement can be added for inserting text after the entire input is processed:
kelly is in /etc> ls −l | \
awk '/\<[a|x].*\.conf$/ { print $9 } END { print \
"Can I do anything else for you, mistress?" }'
Chapter 6. The GNU awk programming language
73