Linux / Unix: Awk Print Variable

by on January 15, 2011 · 0 comments· LAST UPDATED February 15, 2013

in

How do I print variables using Awk interpreted programming language under Linux or Unix like operating systems?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Requirementsawk
Estimated completion timeN/A

Awk pattern scanning and processing language. It is small, fast, and simple. It has a clean syntax and most useful for text processing. awk has built-in variables that are automatically set. For example, $0 variable holds the entire current input line. In this example, print hello world using awk:

 
echo 'Hello world' | awk '{ print $0 }'
 

Sample outputs:

Hello world

In this following example, pass two values to awk to print addition:

 
echo 3 4 | awk '{ print $1 + $2 }'
 

Sample outputs:

7

To print third word from input, enter:

 
echo This is a test |awk '{print $3}'
 

Sample outputs:

a

Printing a text file

Create a file called foo.txt:
$ cat foo.txt
Sample outputs:

Holding on to anger is like grasping a hot coal with the intent of throwing it at someone else; you are the one who gets burned.
In a controversy the instant we feel anger we have already ceased striving for the truth, and have begun striving for ourselves.

To print the entire file line by line, enter:

 
awk '{ print }' foo.txt
 

OR

 
awk '{ print $0 }' foo.txt
 

awk define and print variable

Create a variable called x and y:

 
awk 'BEGIN{x=3; y=4;}END{ print "x=" x " and y=" y}'</dev/null
 

To print total of x and y, enter:

 
echo|awk 'BEGIN{x=3; y=4; total=0}{ total= x+y}END{ print x " + " y " = " total }'
 

Sample outputs:

7

Say hello to printf

To format and print use a printf statement. The printf works like c printf.

 
echo Total 5000.5686 | awk '{ printf "%s $%.2f\n", $1, $2 }'
 

Sample outputs:

Total $5000.57

See awk man page for more details:
$ man awk

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , , ,

Previous Faq:

Next Faq: