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 />

Let an example input file "countries", contain fields "country", "area", "population", "continent"<br />

awk '{ print $2, $1 }' filel # output column 2 & 1<br />

awk '{ print NR, $0 }' filel # add line numbers<br />

awk '{ printf "%10s %6d %6d\n", $1, $2 ,$3 }' filel<br />

{ if ($4 == "ASIA") print > "ASIA"<br />

if ($4 == "EUROPE") print > "EUROPE"}<br />

{ if ($2 == "XX") print | "mail joe" }<br />

{ print $1 | "sort" }<br />

{ print ... | "cat -v > /dev/tty" }<br />

! Patterns<br />

Certain words<br />

BEGIN { FS="\t"<br />

printf "Country\t\tArea\tPopulation\tContinent\n\n"<br />

}<br />

{ printf "%-10s\t%6d\t%6d\t\t%-14s\n", $1,$2,$3,$4 }<br />

END { print "The number of records is", NR }<br />

Arithmetic relational expressions<br />

$3 >100<br />

Regular expressions<br />

/xly/ # contains ei<strong>the</strong>r x or y<br />

/ax+b/ # 1 or more x's between a and b<br />

/ax?b/ # 0 or more x's between a and b<br />

/a.b/ # any character between a and b<br />

/ax*b/ # 0 or more x’s between a and b<br />

Combinations of above<br />

$2 >= 3000 && $3 >= 100 # AND<br />

$4 == "Asia" || $4 == "Africa" # OR<br />

$4 ~ /"Asia|^"Africa/ # matches<br />

! Pattern Ranges<br />

patternl, pattern2 ( action )<br />

# all lines between pattern1 and pattern 2<br />

e.g.<br />

/Canada/,/Brazil/ {…}<br />

NR == 2, NR == 5 {…}<br />

! Actions<br />

Sequence of action statements separated by newlines<br />

# expressions<br />

{ print $1, (1000000 * $3) / ($2 * 1000)}<br />

# variables<br />

/Asia/ { pop += $3; ++n }<br />

END { print "total population of", n, "Asian countries is", pop }<br />

# initialisation of variables<br />

maxpop < $3 {<br />

maxpop = $3<br />

country = $1<br />

}<br />

END { print country, maxpop }<br />

# field variables<br />

48

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

Saved successfully!

Ooh no, something went wrong!