16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Unix</strong> Tools<br />

awk '$3 > 0 { print $1, $2 * $3 }' employee.data<br />

Mark 85<br />

Sue 180<br />

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br />

UBUNTU: mawk<br />

Usage: mawk [-W option] [-F value] [-v var=value] [--] 'program text' [filename]<br />

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br />

! Program structure<br />

pattern ( action )<br />

every input line is tested using 'pattern'<br />

! Running AWK<br />

awk 'program' input files<br />

awk -f progfile input files<br />

! Output<br />

{ print $0 } print entire line<br />

{ print $1, $3 } print first and third fields<br />

{ print NF, $1, $NF }print number of fields and first and last fields<br />

{ print NR, $0 } print number of records and line prefix each line <strong>with</strong> line number<br />

{ printf("pay for", $1, "is", $2 * $3) } place text in output<br />

{ printf("pay for %-8s is $%6.2f\n", $1, $2 * $3) } formatted output<br />

! Selection<br />

$2 >= 5<br />

$1 == "Sue"<br />

/Sue/<br />

$2 >= 4 || $3 >= 20<br />

!($2 < 4 && $3 < 20)<br />

# data validation<br />

NF != 3 {print $0, "number of fields is not equal to 3"}<br />

$2 < 5 {print $0, "rate is below minimum wage"}<br />

$3 < 0 {print $0, "negative hours worked"}<br />

$3 > 60 {print $0, "too many hours worked"}<br />

# add headings to input file<br />

BEGIN {print "NAME RATE HOURS", print ""}<br />

{ print }<br />

! Computing<br />

$3 > 15 { emp = emp + 1 }<br />

END { print emp, "employees worked more than 15 hours" }<br />

END { print NR, "employees"}<br />

{ pay = pay + $2 * $3 }<br />

END { print NR, "employees"}<br />

print "average pay is", pay/NR<br />

}<br />

$2 > maxrate { maxrate = $2; maxemp = $1 }<br />

END { print "highest hourly rate:", maxrate, "for", maxemp }<br />

# string concatenation<br />

{ names = names $1" "}<br />

END { print names }<br />

44

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!