-------------------------------------------------------------------------
HANDY ONE-LINERS FOR AWK (Unix stream editor) Apr. 17, 2001
compiled by Eric Pement <[email protected]> version 0.1
Latest version of this file is usually at:
http://www.student.northpark.edu/pemente/awk/awk1line.txt
USAGE:
Unix: awk '/pattern/ {print "$1"}' # standard Unix shells
DOS/Win: awk '/pattern/ {print "$1"}' # okay for DJGPP compiled
awk "/pattern/ {print \"$1\"}" # required for Mingw32 compile
In the following examples, the current version of awk/nawk is assumed.
If an example is peculiar to GNU awk and will not run under "vanilla"
awk, the command 'gawk' will be used. Please notify me of any errors
or additional one-line commands (total length under 65 characters). I
usually try to put the shortest script first.
FILE SPACING:
# double space a file
awk '1;{print ""}'
awk 'BEGIN{ORS="\n\n"};1'
# double space a file which already has blank lines in it. Output file
# should contain no more than one blank line between lines of text.
awk
# triple space a file
awk '1;{print "\n"}'
# undo double-spacing (assumes even-numbered lines are always blank)
awk 'n;d'
NUMBERING AND CALCULATIONS:
# precede each line by its line number FOR THAT FILE (left alignment).
# Using a tab (\t) instead of space will preserve margins.
awk '{print FNT "\t" $0}' files*
# precede each line by its line number FOR ALL FILES TOGETHER, with tab.
awk '{print NR "\t" $0}' files*
# number each line of a file (number on left, right-aligned)
awk = filename | sed 'N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /'
# number each line of file, but only print numbers if line is not blank
awk '/./=' filename | sed '/./N; s/\n/ /'
# count lines (emulates "wc -l")
awk 'END{print NR}'
TEXT CONVERSION AND SUBSTITUTION:
# IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
awk 's/.$//' # assumes that all lines end with CR/LF
awk 's/^M$//' # in bash/tcsh, press Ctrl-V then Ctrl-M
awk 's/\x0D$//' # gsed 3.02.80, but top script is easier
# IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format
awk "s/$/`echo -e \\\r`/" # command line under ksh
awk 's/$'"/`echo \\\r`/" # command line under bash
awk "s/$/`echo \\\r`/" # command line under zsh
awk 's/$/\r/' # gsed 3.02.80
# IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format
awk "s/$//" # method 1
awk -n p # method 2
# IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format
# Cannot be done with DOS versions of sed. Use "tr" instead.
tr -d \r <infile >outfile # GNU tr version 1.22 or higher
# delete leading whitespace (spaces, tabs) from front of each line
# aligns all text flush left
awk 's/^[ \t]*//' # see note on '\t' at end of file
# delete trailing whitespace (spaces, tabs) from end of each line
awk 's/[ \t]*$//' # see note on '\t' at end of file
# delete BOTH leading and trailing whitespace from each line
awk 's/^[ \t]*//;s/[ \t]*$//'
# insert 5 blank spaces at beginning of each line (make page offset)
awk 's/^/ /'
# align all text flush right on a 79-column width
awk -e :a -e 's/^.\{1,78\}$/ &/;ta' # set at 78 plus 1 space
# center all text in the middle of 79-column width. In method 1,
# spaces at the beginning of the line are significant, and trailing
# spaces are appended at the end of the line. In method 2, spaces at
# the beginning of the line are discarded in centering the line, and
# no trailing spaces appear at the end of lines.
awk -e :a -e 's/^.\{1,77\}$/ & /;ta' # method 1
awk -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/' # method 2
# substitute (find and replace) "foo" with "bar" on each line
awk 's/foo/bar/' # replaces only 1st instance in a line
awk 's/foo/bar/4' # replaces only 4th instance in a line
awk 's/foo/bar/g' # replaces ALL instances in a line
awk 's/\(.*\)foo\(.*foo\)/\1bar\2/' # replace the next-to-last case
awk 's/\(.*\)foo/\1bar/' # replace only the last case
# substitute "foo" with "bar" ONLY for lines which contain "baz"
awk '/baz/s/foo/bar/g'
# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
awk '/baz/!s/foo/bar/g'
# change "scarlet" or "ruby" or "puce" to "red"
awk 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g' # most seds
gawk 's/scarlet\|ruby\|puce/red/g' # GNU sed only
# reverse order of lines (emulates "tac")
# bug/feature in HHsed v1.5 causes blank lines to be deleted
awk '1!G;h;$!d' # method 1
awk -n '1!G;h;$p' # method 2
# reverse each character on the line (emulates "rev")
awk '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'
# join pairs of lines side-by-side (like "paste")
awk '$!N;s/\n/ /'
# if a line ends with a backslash, append the next line to it
awk -e :a -e '/\\$/N; s/\\\n//; ta'
# if a line begins with an equal sign, append it to the previous line
# and replace the "=" with a single space
awk -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D'
# add commas to numeric strings, changing "1234567" to "1,234,567"
gawk ':a;s/\B[0-9]\{3\}\>/,&/;ta' # GNU sed
awk -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' # other seds
# add commas to numbers with decimal points and minus signs (GNU sed)
gawk ':a;s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g;ta'
# add a blank line every 5 lines (after lines 5, 10, 15, 20, etc.)
gawk '0~5G' # GNU sed only
awk 'n;n;n;n;G;' # other seds
SELECTIVE PRINTING OF CERTAIN LINES:
# print first 10 lines of file (emulates behavior of "head")
awk 'NR < 11'
# print first line of file (emulates "head -1")
awk 'NR<2'
awk 'NR == 1'
# print the last 10 lines of a file (emulates "tail")
awk -e :a -e '$q;N;11,$D;ba'
# print the last 2 lines of a file (emulates "tail -2")
awk '$!N;$!D'
# print the last line of a file (emulates "tail -1")
awk 'END{print}'
# print only lines which match regular expression (emulates "grep")
awk '/regex/'
# print only lines which do NOT match regexp (emulates "grep -v")
awk '!/regex/'
# print the line immediately before a regex, but not the line
# containing the regex
awk '/regex/{print x};{x=$0}'
# print the line immediately after a regex, but not the line
# containing the regex
awk '/regex/{getline;print}'
# print 1 line of context before and after regexp, with line number
# indicating where the regexp occurred (similar to "grep -A1 -B1")
awk -n -e '/regexp/{=;x;1!p;g;$!N;p;D;}' -e h
# grep for AAA and BBB and CCC (in any order)
awk '/AAA/!d; /BBB/!d; /CCC/!d'
# grep for AAA and BBB and CCC (in that order)
awk '/AAA.*BBB.*CCC/!d'
# grep for AAA or BBB or CCC (emulates "egrep")
awk -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d # most seds
gawk '/AAA\|BBB\|CCC/!d' # GNU sed only
# print paragraph if it contains AAA (blank lines separate paragraphs)
# HHsed v1.5 must insert a 'G;' after 'x;' in the next 3 scripts below
awk -e '/./{H;$!d;}' -e 'x;/AAA/!d;'
# print paragraph if it contains AAA and BBB and CCC (in any order)
sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;/BBB/!d;/CCC/!d'
# print paragraph if it contains AAA or BBB or CCC
awk -e '/./{H;$!d;}' -e 'x;/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d
gawk '/./{H;$!d;};x;/AAA\|BBB\|CCC/b;d' # GNU sed only
# print only lines of 65 characters or longer
awk 'length > 64'
# print only lines of less than 65 characters
awk 'length < 64'
# print section of file from regular expression to end of file
awk '/regex/,EOF'
# print section of file based on line numbers (lines 8-12, inclusive)
awk 'NR==8,NR==12'
# print line number 52
awk 'NR==52'
# beginning at line 3, print every 7th line
gawk -n '3~7p' # GNU sed only
awk -n '3,${p;n;n;n;n;n;n;}' # other seds
# print section of file between two regular expressions (inclusive)
awk -n '/Iowa/,/Montana/p' # case sensitive
SELECTIVE DELETION OF CERTAIN LINES:
# print all of file EXCEPT section between 2 regular expressions
awk '/Iowa/,/Montana/d'
# delete duplicate, consecutive lines from a file (emulates "uniq").
# First line in a set of duplicate lines is kept, rest are deleted.
awk '$!N; /^\(.*\)\n\1$/!P; D'
# delete duplicate, nonconsecutive lines from a file. Beware not to
# overflow the buffer size of the hold space, or else use GNU awk.
awk -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'
# delete the first 10 lines of a file
awk '1,10d'
# delete the last line of a file
awk '$d'
# delete the last 2 lines of a file
awk 'N;$!P;$!D;$d'
# delete the last 10 lines of a file
awk -e :a -e '$d;N;2,10ba' -e 'P;D' # method 1
awk -n -e :a -e '1,10!{P;N;D;};N;ba' # method 2
# delete every 8th line
gawk '0~8d' # GNU sed only
awk 'n;n;n;n;n;n;n;d;' # other seds
# delete ALL blank lines from a file (same as "grep '.' ")
awk NF
awk '/./'
# delete all CONSECUTIVE blank lines from file except the first; also
# deletes all blank lines from top and end of file (emulates "cat -s")
sed '/./,/^$/!d' # method 1, allows 0 blanks at top, 1 at EOF
awk '/^$/N;/\n$/D' # method 2, allows 1 blank at top, 0 at EOF
# delete all CONSECUTIVE blank lines from file except the first 2:
awk '/^$/N;/\n$/N;//D'
# delete all leading blank lines at top of file
awk '/./,$!d'
# delete all trailing blank lines at end of file
awk -e :a -e '/^\n*$/{$d;N;ba' -e '}' # works on all awks
awk -e :a -e '/^\n*$/N;/\n$/ba' # ditto, except for gsed 3.02*
# delete the last line of each paragraph
awk -n '/^$/{p;h;};/./{x;/./p;}'
SPECIAL APPLICATIONS:
# remove nroff overstrikes (char, backspace) from man pages. The 'echo'
# command may need an -e switch if you use Unix System V or bash shell.
awk "s/.`echo \\\b`//g" # double quotes required for Unix environment
awk 's/.^H//g' # in bash/tcsh, press Ctrl-V and then Ctrl-H
awk 's/.\x08//g' # hex expression for sed v1.5
# get Usenet/e-mail message header
awk '/^$/q' # deletes everything after first blank line
# get Usenet/e-mail message body
awk '1,/^$/d' # deletes everything up to first blank line
# get Subject header, but remove initial "Subject: " portion
awk '/^Subject: */!d; s///;q'
# get return address header
awk '/^Reply-To:/q; /^From:/h; /./d;g;q'
# parse out the address proper. Pulls out the e-mail address by itself
# from the 1-line return address header (see preceding script)
awk 's/ *(.*)//; s/>.*//; s/.*[:<] *//'
# add a leading angle bracket and space to each line (quote a message)
awk 's/^/> /'
# delete leading angle bracket & space from each line (unquote a message)
awk 's/^> //'
# remove most HTML tags (accommodates multiple-line tags)
awk -e :a -e 's/<[^>]*>//g;/</N;//ba'
# extract multi-part uuencoded binaries, removing extraneous header
# info, so that only the uuencoded portion remains. Files passed to
# sed must be passed in the proper order. Version 1 can be entered
# from the command line; version 2 can be made into an executable
# Unix shell script. (Modified from a script by Rahul Dhesi.)
awk '/^end/,/^begin/d' file1 file2 ... fileX | uudecode # vers. 1
awk '/^end/,/^begin/d' "$@" | uudecode # vers. 2
# zip up each .TXT file individually, deleting the source file and
# setting the name of each .ZIP file to the basename of the .TXT file
# (under DOS: the "dir /b" switch returns bare filenames in all caps).
echo @echo off >zipup.bat
dir /b *.txt | awk "s/^\(.*\)\.TXT/pkzip -mo \1 \1.TXT/" >>zipup.bat
TYPICAL USE:
Sed takes one or more editing commands and applies all of
them, in sequence, to each line of input. After all the commands have
been applied to the first input line, that line is output and a second
input line is taken for processing, and the cycle repeats. The
preceding examples assume that input comes from the standard input
device (i.e, the console, normally this will be piped input). One or
more filenames can be appended to the command line if the input does
not come from stdin. Output is sent to stdout (the screen). Thus:
cat filename | sed '10q' # uses piped input
sed '10q' filename # same effect, avoids a useless "cat"
sed '10q' filename > newfile # redirects output to disk
For additional syntax instructions, including the way to apply editing
commands from a disk file instead of the command line, consult "sed &
awk, 2nd Edition," by Dale Dougherty and Arnold Robbins (O'Reilly,
1997; http://www.ora.com), "UNIX Text Processing," by Dale Dougherty
and Tim O'Reilly (Hayden Books, 1987) or the tutorials by Mike Arst
distributed in U-SEDIT2.ZIP (many sites). To fully exploit the power
of sed, one must understand "regular expressions." For this, see
"Mastering Regular Expressions" by Jeffrey Friedl (O'Reilly, 1997).
The manual ("man") pages on Unix systems may be helpful (try "man
sed", "man regexp", or the subsection on regular expressions in "man
ed"), but man pages are notoriously difficult. They are not written to
teach sed use or regexps to first-time users, but as a reference text
for those already acquainted with these tools.
QUOTING SYNTAX: The preceding examples use single quotes ('...')
instead of double quotes ("...") to enclose editing commands, since
sed is typically used on a Unix platform. Single quotes prevent the
Unix shell from intrepreting the dollar sign ($) and backquotes
(`...`), which are expanded by the shell if they are enclosed in
double quotes. Users of the "csh" shell and derivatives will also need
to quote the exclamation mark (!) with the backslash (i.e., \!) to
properly run the examples listed above, even within single quotes.
Versions of sed written for DOS invariably require double quotes
("...") instead of single quotes to enclose editing commands.
USE OF '\t' IN SED SCRIPTS: For clarity in documentation, we have used
the expression '\t' to indicate a tab character (0x09) in the scripts.
However, most versions of sed do not recognize the '\t' abbreviation,
so when typing these scripts from the command line, you should press
the TAB key instead. '\t' is supported as a regular expression
metacharacter in awk, perl, and HHsed, sedmod, and GNU sed v3.02.80.
VERSIONS OF SED: Versions of sed do differ, and some slight syntax
variation is to be expected. In particular, most do not support the
use of labels (:name) or branch instructions (b,t) within editing
commands, except at the end of those commands. We have used the syntax
which will be portable to most users of sed, even though the popular
GNU versions of sed allow a more succinct syntax. When the reader sees
a fairly long command such as this:
sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d
it is heartening to know that GNU sed will let you reduce it to:
sed '/AAA/b;/BBB/b;/CCC/b;d' # or even
sed '/AAA\|BBB\|CCC/b;d'
In addition, remember that while many versions of sed accept a command
like "/one/ s/RE1/RE2/", some do NOT allow "/one/! s/RE1/RE2/", which
contains space before the 's'. Omit the space when typing the command.
-------------------------------------------------------------------------
From: [email protected] (Peter Jaspers-Fayer)
Newsgroups: comp.lang.awk
Subject: Silly Awk Idioms
Date: 17 Dec 1996 21:51:53 GMT
Organization: University of Guelph
Lines: 60
Message-ID: <[email protected]>
NNTP-Posting-Host: hapi.cs.uoguelph.ca
X-Newsreader: TIN [version 1.2 PL2]
Xref: newshub.csu.net comp.lang.awk:3735
What can I say, I'm collecting. It may be silly to some of you, but in
compiling this list, I've learned a few things. I have noted a few strange
differences between the awks running on different platforms (over and above
the usual awk/nawk differences).
Inspired by recent threads on comp.lang.awk, I began collecting
these little one-liners to serve as examples of "awk idioms".
Some are more obscure than others. The real short ones make use
of the "implied print" feature of most newer awk (nawk) dialects.
I wouldn't mind collecting more of these 1-liners ( < 25 chars or so
long, the shorter, the better).
All of these work on a more-or-less current awk, (I don't have
gawk/tawk/mawk), and I'm not interested in (say) gawk-only idioms.
Hopefully the table below is not too complex. If you test on another
platform, please send me results.
1 SGI IRIX 5.3 awk (-> oawk)
2 SGI IRIX 5.3 nawk
3 HPUX 10.20 awk
4 SunOS 4.1.3 awk
5 Solaris 5.5.1
23 awk '$2="foo"' - replace word 2 on all lines with "foo"
12345 awk '($2=="foo")' - copy only if word 2 == "foo"
12345 awk '$1~/foo/{print $3}' - print $3 of lines with "foo" as part of $1
12345 awk '{$1+=0; print}' or
23 awk '$1+=0' - 0(zero)+$1 removes leading zeros in $1
12345 awk '{s+=$3}END{print s}' - Sum the 3rd column
12 45 awk '{$1=$1; print}' - Remove all redundant whitespace in a line.*
23 awk 'gsub(/[ ]+/," ")' - Remove all redundant spaces in a line
-------------------------------------------------------------------------------
* Strangely, the $1=$1 assignment RUNS on HPUX, but is a no-op. (?)
--
/PJ "You can't grep dead trees" [email protected]
(519)824-4120x6309
------
awk one liners (collected from various sources by Eric Pement,
generally use gawk where possible)
# print and sort the login names of all users
awk 'BEGIN { FS = ":" }; { print $1 | "sort" }' /etc/passwd
# print the number of fields in each line
awk '{ print NF }'
# print the last field of each line
awk '{ print $NF }'
# print the last field of the last line
awk '{ field = $NF }; END{ print field }'
# print every line with more than 4 fields
awk 'NF > 4'
# print every line where the value of the last field is > 4
awk '$NF > 4'
# print the total number of fields ("words") in all lines
awk '{ total = total + NF }; END {print total}' file
# print the total number of lines that contain "Beth"
awk '/Beth/ { nlines++ }; END {print nlines}' file
# print the largest first field and the line that contains it
awk '$1 > max {max=$1; maxline=$0}; END{ print max, maxline}'
# print the number of fields in each line, followed by the line
awk '{ print NF ":" $0 } '
# print the first 2 fields, in opposite order, of every line
awk '{print $2, $1}' file
# switch the first 2 fields of every line
awk '{temp = $1; $1 = $2; $2 = temp}' file
# print every line, deleting the second field of that line
awk '{ $2 = ""; print }'
# print in reverse order the fields of every line
awk '{for (i=NF; i>0; i--) printf("%s ",i);printf ("\n")}' file
# print the sums of the fields of every line
awk '{sum=0; for (i=1; i<=NF; i++) sum = sum+i; print sum}'
# add all fields in all lines and print the sum
awk '{for (i=1; i<=NF; i++) sum = sum+1}; END {print sum}'
# print every line after replacing each field with its absolute value
awk '{for (i=1; i<=NF; i++) if ($i < 0) $i = -$i; print }'
# remove duplicate, nonconsecutive lines from an unsorted file
awk "! a[$0]++" # most concise script
awk "!($0 in a) {a[$0];print}" # most efficient script