Linux / Unix: Awk Print Variable

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

Tutorial details
Difficulty level Easy
Root privileges No
Requirements awk
Est. reading time N/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


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum