Awk Tutorial
Awk Tutorial
About
Free eBook
Archives
Best of the Blog
Contact
20 Like 31 Tw eet 12
This is the first article on the new awk tutorial series. Well be posting several articles on awk in the upcoming weeks that will cover all features of awk with
practical examples.
In this article, let us review the fundamental awk working methodology along with 7 practical awk print examples.
Note: Make sure you review our earlier Sed Tutorial Series.
The Awk is mostly used for pattern scanning and processing. It searches one or more files to see if they contain lines that matches with the specified patterns and
then perform associated actions.
Awk reads from a file or from its standard input, and outputs to its standard output. Awk does not get along with non-text files.
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 1/13
Syntax:
Let us create employee.txt file which has the following content, which will be used in the
examples mentioned below.
$cat employee.txt
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
In the above example pattern is not given. So the actions are applicable to all the lines.
Action print with out any argument prints the whole line by default. So it prints all the
lines of the file with out fail. Actions has to be enclosed with in the braces.
Awk Example 2. Print the lines which matches with the pattern.
$ awk '/Thomas/
> /Nisha/' employee.txt
100 Thomas Manager Sales $5,000
400 Nisha Manager Marketing $9,500
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 2/13
In the above example it prints all the line which matches with the Thomas or Nisha. It has two patterns. Awk accepts any number of patterns, but each set
(patterns and its corresponding actions) has to be separated by newline.
Awk has number of built in variables. For each record i.e line, it splits the record delimited by whitespace character by default and stores it in the $n variables. If
the line has 4 words, it will be stored in $1, $2, $3 and $4. $0 represents whole line. NF is a built in variable which represents total number of fields in a record.
In the above example $2 and $5 represents Name and Salary respectively. We can get the Salary using $NF also, where $NF represents last field. In the print
statement , is a concatenator.
Awk has two important patterns which are specified by the keyword called BEGIN and END.
Syntax:
BEGIN { Actions}
{ACTION} # Action for everyline in a file
END { Actions }
Actions specified in the BEGIN section will be executed before starts reading the lines from the input.
END actions will be performed after completing the reading and processing the lines from the input.
In the above example, it prints headline and last file for the reports.
Awk Example 5. Find the employees who has employee id greater than 200
$ awk '$1 >200' employee.txt
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
In the above example, first field ($1) is employee id. So if $1 is greater than 200, then just do the default print action to print the whole line.
Now department name is available as a fourth field, so need to check if $4 matches with the string Technology, if yes print the line.
Operator ~ is for comparing with the regular expressions. If it matches the default action i.e print whole line will be performed.
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 3/13
Awk Example 7. Print number of employees in Technology department
The below example, checks if the department is Technology, if it is yes, in the Action, just increment the count variable, which was initialized with zero in the
BEGIN section.
Then at the end of the process, just print the value of count which gives you the number of employees in Technology department.
Recommended Reading
Sed and Awk 101 Hacks, by Ramesh Natarajan. I spend several hours a day on UNIX / Linux environment dealing with text files (data,
config, and log files). I use Sed and Awk for all my my text manipulation work. Based on my Sed and Awk experience, Ive written Sed and Awk 101 Hacks
eBook that contains 101 practical examples on various advanced features of Sed and Awk that will enhance your UNIX / Linux life. Even if youve been using
Sed and Awk for several years and have not read this book, please do yourself a favor and read this book. Youll be amazed with the capabilities of Sed and
Awk utilities.
Tags: Awk ACTION Block, Awk BEGIN Block, Awk Begin End, Awk END Block, Awk Tutorial Examples, Linux Awk Examples, Linux Awk Tutorial, Unix
Awk Examples, Unix Awk Tutorial
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 4/13
I have only just started reading these articles. So far I think they are well written and the explanations are clearly done with an awareness as to how they
might possibly be misunderstood and hence extra layers of detail are presented where that might happen. For example, pointing out that the tilde (~) is used
to compare with regular expressions when the reader might have otherwise expected an equals sign without the explanation the reader might have decided
that the tilde represented the same thing as an equals sign.
Kind Regards
Steve
Thank you for the post here on awk. I use it frequently, but it is always good to have some updates and reminders. Happy New Year.
Best Regards,
Lawrence
Hi Good article now I know what ark is, and what I could use it for well written. I follow you now on twitter!
@Steve,
Yeah. ~ can be little confusing in this context, if not explained properly. Thanks for you comment.
@Daniel,
Yeah. Most other readers of the blog are in similar position like you. So, we are here to give constant updated and remainders of the functionality that they
already know.
@Lawrence, Harsh,
Thanks for the very nice comment. Im glad you liked this article.
@Knusper,
Nandraka Ulladhu!!!
I guess the example 2 can be done without a new line like below? Pattern as regex.
Hi,
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 5/13
but its not working it is not creating filename1 or filename2, how can I do this?
thanks?
using awk command, i hav to print manager total salary and trainee total salary.
i need a program.. can any one plz post it
Hi..@Avinash..
u can try this one.
awk BEGIN {man_sal=0;trainee_sal=0;}
$3 ~/manager/ {man_sal+=$NF}
/trainee/ {trainee_sal+=$NF}
END {print Total salary of managers and trainees are=man_sal,trainee_sal} in_file.name
Thanks for AWK tutorials ,it was very help ful to me.
@ vikas
thanks you
hi all,
if i have a issue file like:
if exit and login again i should get the increment of the first field like
its is very useful for the beginning learners and its is very help in exams time also
This is very help. How about if I want to print the salary seperated by commas, e.g. 2,000 instead of 2000
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 6/13
18 sudha February 2, 2011 at 12:38 pm
Hi,
I found this article to be very useful. Anybody who wants to know what an awk is , this will give a fair idea. Looking forward to similar articles on other
topics of unix.
Thanks
Hi,
Good,
Please try teach in Youtube to try differntly.
It will be more success.
Keep it up,
I need to take an exam on awk, let me see how much I can successed.
I have read few geekstuff articles until now, explanations provided are the best I have ever seen so far! Great job Thanks a lot
hi,
i have the question that how to using print command awk to sort or transpose this data from many coloums to 2 columns only
#input file
NAME JAN FEB MARCH APRIL MAY JUNE JULY
- - -
BEN 5,000 6,000 7,000 8,000 6,500 7,500 9,000
YONG 4,000 5,500 6,000 5,800 7,000 8,000 8,5000
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 7/13
I know its late, but
#!/bin/bash
awk {
# skip the first two lines
if (NR == 1 || NR == 2)
continue
Nice site! I learned some new things about sed I didn't know.
We have duplicate titles in our library database. I am able to find the duplicates but cant figure out how to print the line above that matches the regular
expression and that line also has the same expression. Each set of duplicates has a space between: example. I would match on SERSOL-EBK
hi..
i want to capture these data through awk.
596583.46875(E) 4924298.34375(N)
geology@PERMANENT in PERMANENT (9)sand
604960.78125(E) 4922837.53125(N)
geology@PERMANENT in PERMANENT (6)shale
596911.40625(E) 4920512.15625(N)
geology@PERMANENT in PERMANENT (4)sandstone
Thank you for this site you really saved me a lot of time. This is easy to follow and really helped me understand awk.
Hi All,
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 8/13
I have a log file with the contents as below.
This will have entities based on the timestamp shown above (i.e. 09:30:51, 09:30:52, etc).
Now my requirement is, I need to get the number of entries per an hour.
For example if the first record is with timestamp as 09:30:51.
Till 10:30:51 timestamps record I need to get the number of records.
Thanks,
Sudarshan
instr=str"substr($1,1,12),substr($2,1,13);
#print str1 is: instr;
}
else if ((NR % 3)==2)
{#print NR2 is:NR;
instr=instr,$1,""ashale"");
print instr >insert.sql;
}
else ((NR % 3)==0)
{# print NR3 is:NR;
str=insert into mytable values(;
}
fi}
END{} log.txt
Leave a Comment
Name
Website
Submit
Previous post: Can You Top This? 15 Practical Linux Top Command Examples
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 9/13
RSS Twitter Facebook
Search
EBOOKS
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 10/13
POPULAR POSTS
12 Amazing and Essential Linux Books To Enrich Your Brain and Library
50 UNIX / Linux Sysadmin Tutorials
50 Most Frequently Used UNIX / Linux Commands (With Examples)
How To Be Productive and Get Things Done Using GTD
30 Things To Do When you are Bored and have a Computer
Linux Directory Structure (File System Structure) Explained with Examples
Linux Crontab: 15 Awesome Cron Job Examples
Get a Grip on the Grep! 15 Practical Grep Command Examples
Unix LS Command: 15 Practical Examples
15 Examples To Master Linux Command Line History
Top 10 Open Source Bug Tracking System
Vi and Vim Macro Tutorial: How To Record and Play
Mommy, I found it! -- 15 Practical Linux Find Command Examples
15 Awesome Gmail Tips and Tricks
15 Awesome Google Search Tips and Tricks
RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
Can You Top This? 15 Practical Linux Top Command Examples
Top 5 Best System Monitoring Tools
Top 5 Best Linux OS Distributions
How To Monitor Remote Linux Host using Nagios 3.0
Awk Introduction Tutorial 7 Awk Print Examples
How to Backup Linux? 15 rsync Command Examples
The Ultimate Wget Download Guide With 15 Awesome Examples
Top 5 Best Linux Text Editors
Packet Analyzer: 15 TCPDUMP Command Examples
The Ultimate Bash Array Tutorial with 15 Examples
3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
Unix Sed Tutorial: Advanced Sed Substitution Examples
UNIX / Linux: 10 Netstat Command Examples
The Ultimate Guide for Creating Strong Passwords
6 Steps to Secure Your Home Wireless Network
Turbocharge PuTTY with 12 Powerful Add-Ons
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 11/13
About The Geek Stuff
My name is Ramesh Natarajan. I will be posting instruction guides, how-to, troubleshooting tips and tricks on Linux, database, hardware,
security and web. My focus is to write articles that will either teach you or help you resolve a problem. Read more about Ramesh Natarajan and the blog.
Support Us
Contact Us
Email Me : Use this Contact Form to get in touch me with your comments, questions or suggestions about this site. You can also simply drop me a line to
say hello!.
Follow us on Twitter
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 12/13
Copyright 20082012 Ramesh Natarajan. All rights reserved | Terms of Service | Advertise
www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/ 13/13