40 likes | 166 Views
awk Challenges. Find out what the following awk scripts do: END { print NR } Print number of records in a file. NR == 10 Print the 10th record of a file. { print $NF } { field = $NF } END { print field } Print all last fields in a file (i.e., last field of each record). NF > 4
E N D
awk Challenges Find out what the following awk scripts do: END { print NR } Print number of records in a file. NR == 10 Print the 10th record of a file. { print $NF } { field = $NF } END { print field } Print all last fields in a file (i.e., last field of each record). NF > 4 Print records of a file that contain more than 4 fields. $NF > 4 { nf = nf + NF } END { print nf } Print number of fields in all records in which the fourth field is larger than 4. Prof. Andrzej (AJ) Bieszczad Email: andrzej@csun.edu Phone: 818-677-4954
awk Challenges Hint: Use the following to try things out: $ awk ‘/one/{print “This line contains \”one\”.”}’ I’ve got one penny. This line contains “one”. Count all records that include string “->” /->/ { nlines = nlines + 1 } END { print nlines } Find the maximum value of the first field of all records and print it along with the whole record $1 > max { max = $1; maxline = $0 } END { print max, maxline } Prof. Andrzej (AJ) Bieszczad Email: andrzej@csun.edu Phone: 818-677-4954
awk Challenges Print all records that are not empty NF > 0 Print all records that are longer than 80 characters length($0) > 80 Print the number of fields in each record along with the record { print NF, $0 } Print all records with reversed first two fields { print $2, $1 } { temp = $1; $1 = $2; $2 = temp; print } Remove the second field from all records { $2 = ""; print } Prof. Andrzej (AJ) Bieszczad Email: andrzej@csun.edu Phone: 818-677-4954
awk Challenges Print all records backwards { for (i = NF; i > 0; i = i - 1) printf(“%s “, $i) printf(“\n”) } Compute and print a sum of all fields in each record { sum = 0 for (i = 1; i <= NF; i = i + 1) sum = sum + $i print sum } Compute and print a concatenation of all fields in whole file { for (i = 1; i <= NF; i = i + 1) sum = sum $i } END { print sum } Prof. Andrzej (AJ) Bieszczad Email: andrzej@csun.edu Phone: 818-677-4954