ONUR AND BRIAN
You may want to discuss the example awk script in the reading….I leave that up to
you all. THANKS!
Laboratory 5: awk Scripting
In this lab session, we will practice using awk. We will be using the file
/gaia/home/hdeshon/ESCI7205/NMSZ.catalog.txt for this practice. Copy this file to your
own home directory. Please turn in this sheet with answers to the italicized questions at
the end of classes. They can be left in the box outside my office door.
Command line awk examples:
1. Reformat the file so that it ordered Origin time, Latitude, Longitude, Depth, Magnitude
awk „{print $1,$2,$3,$4,$5,$1}‟ file
2. Print columns 1, 2, 3, 4 using the “/” as a field separator
awk „-F”/” { print $1,$2,$3,$4}‟ file
3. Print the record number and length of each line
awk „{ print NR,length($0) }‟ file
4. Print fields in reverse order:
awk '{ for (i = NF; i > 0; --i) print $i }' file
5. Print column 1 if column 6 > column 7:
awk '$6 > $7 {print $1}' file
What is another syntax that can be used here?
Possible answer: awk ‘{if ($6>$7) print $1}’ file
6. Count number of lines where column 6 > column 7
awk '$6 > $8 {print i + "1"; i++}' file
Using the unix command wc, find another way to accomplish this task
Possible answer: awk ‘{if ($6>$7) print $0}’ file | wc | awk ‘{print $1}’
7. Print every line after erasing the 2nd and 3rd fields
awk '{$2 = ""; $3 = “”; print}' file
Come up with another solution to this task
Possible answer: awk ‘{print \
$1,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16}’ file
Programming example
8. Add up the magnitude column, and print sum and average:
{ sum += $1 }
END { print "sum is", sum, " average is", s/NR }
9. Print only the last line
{line = $0}
END {print line}
10. Print the total number of lines that contain the word Tiptonville
/Tiptonville/ {nlines = nlines + 1}
END {print nlines}
11. Replace every field by its absolute value
{ for (i = 1; i 0.5) && ($1 1) && ($1 1.5) && ($1 2.0) && ($1 2.5) && ($1 3.0) && ($1 3.5) && ($1 4) {nj = nj+1}
}
END {print na, nb, nc, nd, ne, nf, ng, nh, ni, nj, NR}
13. Find maximum and minimum values present in column 1
Possible solution:
{ NR == 1 {m=$1 ; p=$1}
$1 >= m {m = $1}
$1 <= p {p = $1}
}
END { print "Max = " m, " Min = " p }