Monday, May 11, 2009

awk world

awk executes the instructions for each line of input

$ cat testfile
1
2
3
4

$ awk '{print $1}' testfile
1
2
3
4

$ awk '{print "Hello, World"}' testfile
Hello, World
Hello, World
Hello, World
Hello, World

awk will wait for the input file name and will consider 'ENTER or RETURN' as valid input.

prefixing BEGIN keyword to any script lets awk execute the instructions without waiting for input file.

$ awk 'BEGIN {print "Hello, World"}' <== No input file
Hello, World

This instruction would be executed only once at the beginining.

$ awk 'BEGIN {print "Hello, World"}' testfile
Hello, World

$ awk 'BEGIN {print "Hello, World"} {print $1}' testfile
Hello, World
1
2
3
4


END keyword can be used to add a closing instruction.

$ awk 'BEGIN {print "Hello, World"} {print $1} END {print "Good bye"} ' testfile
Hello, World
1
2
3
4
Good bye

#

No comments:

Post a Comment