Home > Tutorial > AWK

AWK


An AWK command can be broken in three parts.

Syntax

BEGIN { print "START" }
      { print         }
END   { print "STOP"  }

BEGIN, END blocks are optional and run only once. While, in the other hand, the middle block is run for every line of given file. This is the bock where actual processing logic is written.

You can use BEGIN block to set initial parameters, while you can use END block to print result as summary.

Eg.

1. To print number of lines in a file [one time only]

awk 'END{print NR}' filename

2. To Count number of entries for a month

dates.txt
10-Jul-10
23-Jul-10
:
31-Jul-10
1-Aug-10
:
4-Aug-10
5-Aug-10

awk 'BEGIN{FS="-";OFS=","}{$1="";print substr($0,2,length($0))}' dates.txt
| sort |
awk 'BEGIN{
	lastline=$0;
	count=1;
}
{
	if(lastline==$0){
		count+=1;
	}
	else{
		print lastline": "count;
		lastline=$0;
		count=1;
	}
}
END{print lastline": "count;}'

Output:
Aug,10: 5
Jul,10: 22

3. To Remove all spaces & tabs from all fields of a file

awk 'BEGIN {FS="^";OFS="^";}{for (i=1; i<=NF; i++) {gsub(/^[ \t]+|[ \t]+$/,"",$i);} print }' filename > file_name_new
Advertisements
Categories: Tutorial Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: