Thursday, June 25, 2009

basic awk

Built-In AWK Variables

Variable Meaning Default
ARGC Number of command line arguments –
ARGV Array of command line arguments –
FILENAME Name of current input file –
FNR Record number in current file –
FS Controls the input field separator one space
NF Number of fields in current record –
NR Number of records read so far –
OFMT Output format for numbers %.6g
OFS Output field separator one space
ORS Output record separator \n
RLENGTH Length of string matched by match function –
RS Controls the input record separator \n
RSTART Start of string matched by match function –
SUBSEP Subscript separator \034


awk samples:


➨ Print the total number of lines in file to the screen.
→awk ‘END {print NR}’ filename
➨ Prints the 10th input line to the screen.
→awk ‘NR == 10 {print}’ filename
➨ The print command is to print only the first field ($1) of every line found in the file.
→awk ‘{print $1}’ filename
➨ Print the last field of the last input line to the screen.
→awk ‘{field=$NR} END {print field}’ filename
➨ Print all input lines ($0) from file that have more than 4 fields (NF>4).
→awk ‘NF > 4 {print $0}’ filename

➨ Print the values in the first ($1), fourth ($4), and third ($3) fields from every line in the file filename in the listed order to the screen
separated by the output field separator (OFS) which is one space by default.
→awk ‘{print $1, $4, $3}’ filename
➨ This searches for fields that start (^) with MDATA (~/MDATA/) in the first field ($1). For every match, it increments linesdata by one
(++linesdata). After the entire filename has been read, the program prints to the screen the number of lines that met the criteria along
with a little sentence quoting the name of the input file ($FILENAME).
→awk ‘BEGIN {linesdata=0} $1 ~/^MDATA/ {++linesdata} END {print linesdata “ Lines \
start with MDATA in the first field from “ $FILENAME}’ filename
➨ IF the value in the first field in file is equal to 0, THEN the entire line ($0) will be printed to the screen.
→awk ‘($1 == 0) {print $0}’ filename

➨ This will find the largest time value in the first field in the entire file and after finishing reading the file, it will print the maximum time
found in the first field followed by the entire line from which the value came.

→awk ‘($1 > timemax) {timemax = $1; maxinput = $0} \
END {print timemax, maxinput}’ filename
➨ All output from these commands will go to the screen, but you can use UNIX redirection commands to “pipe” the output into another
command or > “redirect” the output to a file or even >> “append” the output to the and of a pre-existing file.
➨ Awk is also very useful when you need to put information in a different format for a script. Just include the formatting awk statement in
your script.




No comments:

Post a Comment