Search tutorial by keyword

How to use AWK

 

In this post we will see how to use "awk" which is an important thing when it comes to scripting as almost all the scripts in bash use "awk"

Normally awk is used with print and in any command we can print the part of the command we need through awk 

If we want to print number of logged in users in machine we know that we use the uptime command 

# uptime

01:03:00 up 1 day, 23:06,  2 users,  load average: 0.01, 0.05, 0.01

Now we want to print the sixth part which is the number of users so we will use 

# uptime | awk ' { print $ 6}'

2

It will show the result as "2"

awk can also used with -F which is known as field separator 

Like if we want to see all the users in linux we have /etc/passwd file 

# awk -F ":" '{print "username: " $1 }' /etc/passwd

It will produces results like following 

username: abrt

username: haldaemon

username: saslauth

username: postfix

username: ntp

username: apache

username: avahi

username: pulse

username: gdm

username: sshd

username: tcpdump

username: ahmed

You can print out multiple things in one line with awk 

#  awk -F ":" '{print "username: " $1  " Path: " $6}' /etc/passwd

It will show results like this 

username: haldaemon Path: /

username: saslauth Path: /var/empty/saslauth

username: postfix Path: /var/spool/postfix

username: ntp Path: /etc/ntp

username: apache Path: /var/www

username: avahi Path: /var/run/avahi-daemon

username: pulse Path: /var/run/pulse

username: gdm Path: /var/lib/gdm

username: sshd Path: /var/empty/sshd

username: tcpdump Path: /

username: ahmed Path: /home/ahmeda

Michael Dudli

Cloud Specialist with more than 10 years experience in the Hosting Business.

Website: www.cloudserver24.com

Kontakt

Verkauf

sales@cloudserver24.com

Support

support@cloudserver24.com