I am now on Twitter! Meet me on Twitter here (my nick is pkrumins.)
Or on Google Buzz and Facebook.

I noticed that Eric Wendelin wrote an article “awk is a beautiful tool.” In this article he said that it was best to introduce Awk with practical examples. I totally agree with Eric.
When I was learning Awk, I first went through Awk - A Tutorial and Introduction by Bruce Barnett, which was full of examples to try out; then I created an Awk cheat sheet to have the language reference in front of me; and finally I went through the famous Awk one-liners (link to .txt file), which were compiled by Eric Pement.
This is going to be a three-part article in which I will explain every single one-liner in Mr. Pement’s compilation. Each part will explain around 20 one-liners. If you follow closely then the explained examples will turn you into a great Awk programmer.
Eric Pement’s Awk one-liner collection consists of five sections:
- 1. File spacing (explained in this part),
- 2. Numbering and calculations (explained in this part)
- 3. Text conversion and substitution (explained in part two),
- 4. Selective printing of certain lines (explained in part three),
- 5. Selective deleting of certain lines (explained in part three).
- 6. String creation, array creation and update on selective printing of certain lines (explained in bonus article).
The first part of the article will explain the first two sections: “File spacing” and “Numbering and calculations.” The second part will explain “Text conversion and substitution”, and the last part “Selective printing/deleting of certain lines.”
I recommend that you print out my Awk cheat sheet before you proceed. This way you will have the language reference in front of you, and you will memorize things better.
These one-liners work with all versions of awk, such as nawk (AT&T’s new awk), gawk (GNU’s awk), mawk (Michael Brennan’s awk) and oawk (old awk).
Let’s start!
1. Line Spacing
1. Double-space a file.
awk '1; { print "" }'
So how does it work? A one-liner is an Awk program and every Awk program consists of a sequence of pattern-action statements “pattern { action statements }“. In this case there are two statements "1" and "{ print "" }". In a pattern-action statement either the pattern or the action may be missing. If the pattern is missing, the action is applied to every single line of input. A missing action is equivalent to '{ print }'. Thus, this one-liner translates to:
awk '1 { print } { print "" }'
An action is applied only if the pattern matches, i.e., pattern is true. Since '1' is always true, this one-liner translates further into two print statements:
awk '{ print } { print "" }'
Every print statement in Awk is silently followed by an ORS - Output Record Separator variable, which is a newline by default. The first print statement with no arguments is equivalent to "print $0", where $0 is a variable holding the entire line. The second print statement prints nothing, but knowing that each print statement is followed by ORS, it actually prints a newline. So there we have it, each line gets double-spaced.
2. Another way to double-space a file.
awk 'BEGIN { ORS="\n\n" }; 1'
BEGIN is a special kind of pattern which is not tested against the input. It is executed before any input is read. This one-liner double-spaces the file by setting the ORS variable to two newlines. As I mentioned previously, statement "1" gets translated to "{ print }", and every print statement gets terminated with the value of ORS variable.
3. Double-space a file so that no more than one blank line appears between lines of text.
awk 'NF { print $0 "\n" }'
The one-liner uses another special variable called NF - Number of Fields. It contains the number of fields the current line was split into. For example, a line “this is a test” splits in four pieces and NF gets set to 4. The empty line “” does not split into any pieces and NF gets set to 0. Using NF as a pattern can effectively filter out empty lines. This one liner says: “If there are any number of fields, print the whole line followed by newline.”
4. Triple-space a file.
awk '1; { print "\n" }'
This one-liner is very similar to previous ones. '1' gets translated into '{ print }' and the resulting Awk program is:
awk '{ print; print "\n" }'
It prints the line, then prints a newline followed by terminating ORS, which is newline by default.
2. Numbering and Calculations
5. Number lines in each file separately.
awk '{ print FNR "\t" $0 }'
This Awk program appends the FNR - File Line Number predefined variable and a tab (\t) before each line. FNR variable contains the current line for each file separately. For example, if this one-liner was called on two files, one containing 10 lines, and the other 12, it would number lines in the first file from 1 to 10, and then resume numbering from one for the second file and number lines in this file from 1 to 12. FNR gets reset from file to file.
6. Number lines for all files together.
awk '{ print NR "\t" $0 }'
This one works the same as #5 except that it uses NR - Line Number variable, which does not get reset from file to file. It counts the input lines seen so far. For example, if it was called on the same two files with 10 and 12 lines, it would number the lines from 1 to 22 (10 + 12).
7. Number lines in a fancy manner.
awk '{ printf("%5d : %s\n", NR, $0) }'
This one-liner uses printf() function to number lines in a custom format. It takes format parameter just like a regular printf() function. Note that ORS does not get appended at the end of printf(), so we have to print the newline (\n) character explicitly. This one right-aligns line numbers, followed by a space and a colon, and the line.
8. Number only non-blank lines in files.
awk 'NF { $0=++a " :" $0 }; { print }'
Awk variables are dynamic; they come into existence when they are first used. This one-liner pre-increments variable ‘a’ each time the line is non-empty, then it appends the value of this variable to the beginning of line and prints it out.
9. Count lines in files (emulates wc -l).
awk 'END { print NR }'
END is another special kind of pattern which is not tested against the input. It is executed when all the input has been exhausted. This one-liner outputs the value of NR special variable after all the input has been consumed. NR contains total number of lines seen (= number of lines in the file).
10. Print the sum of fields in every line.
awk '{ s = 0; for (i = 1; i <= NF; i++) s = s+$i; print s }'
Awk has some features of C language, like the for (;;) { … } loop. This one-liner loops over all fields in a line (there are NF fields in a line), and adds the result in variable ’s’. Then it prints the result out and proceeds to the next line.
11. Print the sum of fields in all lines.
awk '{ for (i = 1; i <= NF; i++) s = s+$i }; END { print s+0 }'
This one-liner is basically the same as #10, except that it prints the sum of all fields. Notice how it did not initialize variable ’s’ to 0. It was not necessary as variables come into existence dynamically. Also notice how it calls “print s+0″ and not just “print s”. It is necessary if there are no fields. If there are no fields, “s” never comes into existence and is undefined. Printing an undefined value does not print anything (i.e. prints just the ORS). Adding a 0 does a mathematical operation and undef+0 = 0, so it prints “0″.
12. Replace every field by its absolute value.
awk '{ for (i = 1; i <= NF; i++) if ($i < 0) $i = -$i; print }'
This one-liner uses two other features of C language, namely the if (…) { … } statement and omission of curly braces. It loops over all fields in a line and checks if any of the fields is less than 0. If any of the fields is less than 0, then it just negates the field to make it positive. Fields can be addresses indirectly by a variable. For example, i = 5; $i = 'hello', sets field number 5 to string 'hello'.
Here is the same one-liner rewritten with curly braces for clarity. The 'print' statement gets executed after all the fields in the line have been replaced by their absolute values.
awk '{
for (i = 1; i <= NF; i++) {
if ($i < 0) {
$i = -$i;
}
}
print
}'
13. Count the total number of fields (words) in a file.
awk '{ total = total + NF }; END { print total+0 }'
This one-liner matches all the lines and keeps adding the number of fields in each line. The number of fields seen so far is kept in a variable named ‘total’. Once the input has been processed, special pattern 'END { … }' is executed, which prints the total number of fields. See 11th one-liner for explanation of why we “print total+0″ in the END block.
14. Print the total number of lines containing word “Beth”.
awk '/Beth/ { n++ }; END { print n+0 }'
This one-liner has two pattern-action statements. The first one is '/Beth/ { n++ }'. A pattern between two slashes is a regular expression. It matches all lines containing pattern “Beth” (not necessarily the word “Beth”, it could as well be “Bethe” or “theBeth333″). When a line matches, variable ‘n’ gets incremented by one. The second pattern-action statement is 'END { print n+0 }'. It is executed when the file has been processed. Note the '+0' in 'print n+0' statement. It forces '0' to be printed in case there were no matches (’n’ was undefined). Had we not put '+0' there, an empty line would have been printed.
15. Find the line containing the largest (numeric) first field.
awk '$1 > max { max=$1; maxline=$0 }; END { print max, maxline }'
This one-liner keeps track of the largest number in the first field (in variable ‘max’) and the corresponding line (in variable ‘maxline’). Once it has looped over all lines, it prints them out. Warning: this one-liner does not work if all the values are negative.
Here is the fix:
awk 'NR == 1 { max = $1; maxline = $0; next; } $1 > max { max=$1; maxline=$0 }; END { print max, maxline }'
16. Print the number of fields in each line, followed by the line.
awk '{ print NF ":" $0 } '
This one-liner just prints out the predefined variable NF - Number of Fields, which contains the number of fields in the line, followed by a colon and the line itself.
17. Print the last field of each line.
awk '{ print $NF }'
Fields in Awk need not be referenced by constants. For example, code like 'f = 3; print $f' would print out the 3rd field. This one-liner prints the field with the value of NF. $NF is last field in the line.
18. Print the last field of the last line.
awk '{ field = $NF }; END { print field }'
This one-liner keeps track of the last field in variable ‘field’. Once it has looped all the lines, variable ‘field’ contains the last field of the last line, and it just prints it out.
Here is a better version of the same one-liner. It’s more common, idiomatic and efficient:
awk 'END { print $NF }'
19. Print every line with more than 4 fields.
awk 'NF > 4'
This one-liner omits the action statement. As I noted in one-liner #1, a missing action statement is equivalent to '{ print }'.
20. Print every line where the value of the last field is greater than 4.
awk '$NF > 4'
This one-liner is similar to #17. It references the last field by NF variable. If it’s greater than 4, it prints it out.
Have fun!
That’s it for Part I one the article. The second part will be on “Text conversion and substitution.”
Have fun learning Awk! It’s a fun language to know. :)
Did you like this post? Subscribe here:
If you really enjoyed the post, I'd appreciate a gift from my geeky Amazon book wishlist. Books would make me more educated and I could write even better posts. Thanks! :)

(24 votes, average: 4.33 out of 5)
|
|
|


September 28th, 2008 at 11:11 am
Nice post. In the comment for item 17, shouldn’t it say ‘f = 3; print $f’ instead of ‘f = 3; print $3′ ?
September 28th, 2008 at 1:42 pm
Amazing! Scientists jsut never cease to amaze me!
September 28th, 2008 at 6:08 pm
Hehe,
Awesome, if the list was a bit longer it would be a must have for me. Can you extend it a bit? :)
Cheers,
September 28th, 2008 at 6:27 pm
Interesting list.
Here’s a useful awk one-liner to kill a hanging Firefox process, including all its parents that are part of Firefox (but not the shell or any “higher” ancestors). This is a real-life example which I wrote and used recently:
UNIX one-liner to kill a hanging Firefox process
- Vasudev
September 28th, 2008 at 9:16 pm
Thanks ! many are exactly what I been lokking for:
Question re #6
So say if I want a new file from the concatenate of
foo.log0,
foo.log1,
foo.log2 (increaing date)
and number all lines of all log files together,
This is the right command ?
awk ‘{ print NR “\t” $0 }’ foo.log* > foo.txt
or should I do:
awk ‘{ print NR “\t” $0 }’ foo.log0 foo.log1 foo.log2 > foo.txt
thanks
September 28th, 2008 at 11:38 pm
[…] Famous Awk One-Liners Explained, Part I - good coders code, great reuse (tags: development awk) […]
September 29th, 2008 at 1:37 am
[…] Famous Awk One-Liners Explained, Part I - good coders code, great reuse - In this article he said that it was best to introduce Awk with practical examples. I totally agree with Erik. […]
September 29th, 2008 at 2:21 am
#10 correction.
replace
with
ditto #11
September 29th, 2008 at 2:46 am
Awesome list Peteris! These examples are great!
September 29th, 2008 at 2:57 am
Miguel, thanks, i fixed that mistake.
Eduard, this is a 3 part article. This is just part one. Parts two and three coming soon.
Goofy_barny, no, it’s “s=s+$i”. It sums the values in each field.
Go_Obama, I also support Obama :) but for your question, do the awk ‘{ print NR “\t” $0 }’ foo.log0 foo.log1 foo.log2 > foo.txt. The other example will put foo.log11 before foo.log2.
October 2nd, 2008 at 5:40 pm
Nice explanation of all the awk one liners, thanks peter.
//Jadu, unstableme.blogspot.com
October 7th, 2008 at 5:55 am
Hello, I have been playing with AWK a little and have this line.
df -h | grep / | grep % | awk '$(NF-1) >= "20%" {print $NF,": ", $(NF-1)}'Everything works great except I have a volume with 3% usage. AWK in my usage of it only appears to evalute the first number of the “20%”.
I have looked around the net some for a resolution to this and read some documentation. I know that it is something simple I am overlooking, but you folks look like you know what you are doing and are active so I ask; What usage of AWK should I implement to make 1 !> 10.
Thanks in advance.
–Sydney
October 7th, 2008 at 6:20 am
Sydney, thanks for your question.
I see a couple of mistakes here. First of all you are using grep twice! Awk can do what grep does itself with the /…/ regex pattern matching.
Here is what I came up with (works in GNU Awk only!):
df -h | awk '/dev/ { if (strtonum($5) >= 20) { print $NF ": " $(NF-1) } }'And this one works in all Awk’s:
df -h | awk '/dev/ { if (match($5, /^[0-9]+/)) { usage = substr($5, RSTART, RLENGTH) if (usage >= 20) { print $NF ": " $(NF-1) } } }'Hope it helps.
October 7th, 2008 at 7:23 am
Thanks so much Peteris,
I am only ever using GNU AWK on Redhat or Ubuntu maybe Debian rarely. So I mutated the first into:
df -h | awk '/\// { if (strtonum($(NF-1)) >= 20) { print $NF ": " $(NF-1) } }'I am guessing that strtonum function that you suggested takes it out of the string world. I was trying to compare a string to a number.
The RegEx /\// found all mounts.
df output is not constant in Red Hat with long mount names
Who knew? So I changed the code to work backwards from the last field.
Thanks a bunch this was an interesting experiment for me that I may turn around and tweak for production.
October 7th, 2008 at 7:31 am
You’re welcome, Sydney.
October 8th, 2008 at 8:38 am
[…] by the success of my “Awk One-Liners Explained” article (30,000 views in first three days), I decided to explain the famous sed one-liners […]
October 8th, 2008 at 3:51 pm
[…] Famous Awk One-Liners Explained, Part I - good coders code, great reuse […]
October 9th, 2008 at 5:38 am
[…] Famous Awk One-Liners Explained, Part I - good coders code, great reuse (tags: reference tips awk unix bash scripting tricks) […]
October 9th, 2008 at 4:35 pm
Nice clearly written examples. I’ve bookmarked it for future reference :)
Thanks!
November 8th, 2008 at 5:45 pm
Great info, I am familiar with Awk but have only used it for very simple field delimiting. I can’t wait to read the rest of this series and also your series on Sed.
November 10th, 2008 at 3:02 pm
Thank you!
but where is the second part? I can’t find it.
December 9th, 2008 at 6:50 am
[…] the previous article series that I have started (creating and marketing a video downloading tool, famous awk one-liners explained, sed one-liners explained and mit algorithms). I just wanted to utilize my excitement and get this […]
December 13th, 2008 at 10:43 am
[…] Awk one-liners. This part will explain Awk one-liners for text conversion and substitution. See part one for introduction of the […]
December 24th, 2008 at 12:02 am
[…] like the famous Awk one-liners, sed one-liners are beautiful, tiny little sed programs that span no more than 1 terminal line. […]
January 5th, 2009 at 4:10 pm
[…] This part will explain Awk one-liners for selective printing and deletion of certain lines. See part one for introduction of the […]
February 9th, 2009 at 4:32 pm
[…] This is an update post on my three-part article Famous Awk One-Liners Explained. […]
February 20th, 2009 at 1:04 am
[…] Awk 1 liners explained: Part1 Part2 Part3 […]
February 21st, 2009 at 1:11 am
Hi. I’ve been trying to understand example 8
awk ‘NF { $0=++a ” :” $0 }; { print }’
but I can’t, can anybody explain a little bit more?
Peter, amzing site, great articles. Congrats
February 21st, 2009 at 1:28 am
Hey Augusto. Now that I look at one-liner #8, it looks pretty ridiculous. But I didn’t write it.
If I wrote it, here is how it would look:
awk '{ print ++a, $0 }'At every line increment variable a, and output it together with the line itself.
The explanation of the original one liner is this:
Every line gets read in variable $0. The one-liner modifies this $0. It appends the contents of variable ‘a’ to the beginning of $0. But before appending ‘a’ it gets incremented by one by ++ unary operator.
February 25th, 2009 at 12:35 pm
[…] all! I am starting yet another article series here. Remember my two articles on Famous Awk One-Liners Explained and Famous Sed One-Liners Explained? They have received more than 150,000 views total and they […]
March 6th, 2009 at 7:36 am
[…] Awk One Liners Explained […]
April 20th, 2009 at 4:01 pm
[…] Famous Awk One-Liners Explained, Part I - good coders code, great reuse […]
May 16th, 2009 at 5:41 pm
[…] [upmod] [downmod] Famous Awk One-Liners Explained, Part I - good coders code, great reuse (www.catonmat.net) 1 points posted 7 months, 2 weeks ago by SixSixSix tags imported opensource […]
June 2nd, 2009 at 10:11 am
[…] Famous Awk One-Liners Explained, Part I - good coders code, great reuse - In this article he said that it was best to introduce Awk with practical examples. I totally agree with Erik. […]
July 27th, 2009 at 1:59 am
[…] to famous Awk one-liners, sed one-liners are short and concise sed programs that span less than one terminal line. They were […]
July 29th, 2009 at 3:31 pm
For Sydney 10/8/2008, who writes:
AWK in my usage of it only appears to evaluate the first number of the “20%”. so I ask; What usage of AWK should I implement to make 1 compare lower than 10.
Unix awk does not have strtonum but you don’t need it, nor substr. The problem is that variables are treated both as string and numeric by the comparison operators. Trick is to typecast to numeric using (0 + expression), or to string using (”" expression), to force the right comparison. For a variable $3 like 17%, use x = 0 + $3 to assign the 17 part to x.
October 10th, 2009 at 8:36 am
[…] dotyczące akw: Part One, Part Two, Part Three, Part Four (bonus). Artykuły dotyczące sed: Part One, Part Two, Part […]
October 27th, 2009 at 7:41 am
[…] Famous Awk One-Liners Explained, Part I: File Spacing, Numbering and Calculations […]
November 3rd, 2009 at 2:49 pm
[…] Perl one-liners is my attempt to create “perl1line.txt” that is similar to “awk1line.txt” and “sed1line.txt” that have been so popular among Awk and Sed […]
December 13th, 2009 at 2:13 pm
[…] Part One: File spacing, Numbering and calculations […]
January 8th, 2010 at 1:14 am
[…] Perl one-liners is my attempt to create “perl1line.txt” that is similar to “awk1line.txt” and “sed1line.txt” that have been so popular among Awk and Sed […]
January 8th, 2010 at 1:47 am
[…] Perl one-liners is my attempt to create “perl1line.txt” that is similar to “awk1line.txt” and “sed1line.txt” that have been so popular among Awk and Sed […]
February 4th, 2010 at 11:01 am
[…] Perl one-liners is my attempt to create “perl1line.txt” that is similar to “awk1line.txt” and “sed1line.txt” that have been so popular among Awk and Sed […]