Program I User
defined Function
awk
'
BEGIN{i=1}
{
my_function(i)
print line[i]
BEGIN{i=1}
{
my_function(i)
print line[i]
i=i+1
}
function my_function(i)
{
}
function my_function(i)
{
if (i==1)
{
print "First"
print "First"
line[1]= "awk"
}
if (i==2)
{
print "Second"
print "Second"
line[2]= "gawk"
}
if (i==3)
{
print "Third"
print "Third"
line[3]= "nawk"
}
}' filename
Field separators
- FS="\t+"
- FS="[[:space:]]+"
Number of fields
- NF == 3
{ print "this particular record has three fields: " $0 }
- if ( NF > 2 ) {
print $1 " "
$2 ":" $3
}
Record number
The record number (NR) is another
handy variable. It will always contain the number of the current
record (awk counts the first record as record number 1).
if
(NR < 10 ) || (NR > 100)
{ print "We are on record number
1-9 or 101+" }
if ( NR >
10 ) {
print "ok, now for
the real information!"
}
Multiline records
Jimmy
the Weasel
100
Pleasant Drive
San
Francisco, CA 12345
Big
Tony
200
Incognito Ave.
Suburbia,
WA 67890
-----------------------
BEGIN
{
FS="\n"
RS=""
}
{
print $1 ", " $2 ", " $3 }
Answer
: //Printing in the single for multi-line records.
Jimmy
the Weasel, 100 Pleasant Drive, San Francisco, CA 12345
Big
Tony, 200 Incognito Ave., Suburbia, WA 67890
OFS and ORS
Output field Separator , Output
record separator
BEGIN
{
FS="\n"
RS=""
OFS=",
"
}
{
print $1, $2, $3 }
-------------------------
BEGIN
{
FS="\n"
RS=""
ORS=""
}
{
x=1
while
( x<NF ) {
print
$x "\t"
x++
}
print
$NF "\n"
}
--------------------------------------------------------------------------------------
Awk Loop Statement
{ for(i=0;i<=10;i++)
{
printf("%d\n", i);
} }'
No comments:
Post a Comment