ch 12 IT244 Introduction to Linux Unix Instructor Bo Sheng 1 Introduction What is AWK Pattern processing language Data driven filter report writer Alfred Aho Peter Weinberger Brian Kernighan ID: 576627
Download Presentation The PPT/PDF document "AWK (" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
AWK (ch 12)
IT244 - Introduction to Linux / Unix Instructor: Bo Sheng
1Slide2
Introduction
What is AWK?Pattern processing languageData driven, filter, report writerAlfred Aho
, Peter Weinberger, Brian Kernighan
awk
, nawk (new awk): from AT&Tgawk (GNU awk)
2Slide3
IntroductionUsage
pattern { action }
awk
‘/
chevy/ {print}’ cars‘’ is recommended BEGIN { } END { }~it244/it244
/scripts/
simple
awk –f simple cars
3Slide4
PatternsMissing pattern
gawk ‘{print}’ carsMissing actiongawk ‘/chevy
/’ cars
Fields
gawk ‘{print $3, $1}’ cars4Slide5
PatternsContains (~)
gawk ‘/h/’ carsgawk ‘$1 ~ /h/’ carsMatch at the beginning(^)/end($)
gawk ‘$1 ~ /^h/’ cars
gawk ‘$3 ~ /5$/’ cars
5Slide6
PatternsComparison
gawk ‘$3 == 1985’ carsgawk ‘$5 <= 3000’ carsgawk ‘$5 > “2000”’ cars
gawk ‘$5 > 2000 && $5<6000’ cars
Range (,)
gawk ‘/volvo/, /bmw/’ cars
gawk ‘/
chevy
/, /ford/’ cars
6Slide7
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}’ carsgawk ‘NR==2, NR==5’ carsFS (field separator) / OFS
(output)
~it244/it244/scripts/fs
gawk –f
fs /etc/
passwd
7Slide8
ExamplesFind the maximum number
~it244/it244/scripts/maxgawk -f max carsCalculate average values
~it244/it244/scripts/summary
gawk -f summary cars
8Slide9
Control Structureif..else
if (condition) {commands} [else {commands}]Example~it244/it244/scripts/
if_demo
while
loop while (condition) {commands}9Slide10
Control Structure
for loopSyntax 1for (init; condition; increment)
{commands}
Example :
~it244/it244/scripts/for1{for (n=1; n<=NF; n++){ print $n }}Syntax 2for (var
in array)
{commands}
10Slide11
Output Format
printfprintf “control-string”, arg1, arg2, …
Control string
%[-][x[.y]]
conv-: left-justifyx: minimum field width, y: precision levelconv: type of conversionExample:
~it244/it244/scripts/
printf_demo
11