Linux / Unix: Awk Print Variable

last updated in Categories

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

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:


To print third word from input, enter:

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

Sample outputs:


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


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:


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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.