 
  % -------------------------------------------
  %  latex generated by: booktolatex.cgi   
  %   from source file : ../htdocs/books/awk/awk-book.txt       
  %                  on: 19 April 2024,  5:34pm         
  %         querystring: books/awk/awk-book.txt  
  %       document-root: /var/www/html
  %         script-name: /cgi-bin/booktolatex.cgi
  %         Server-name: bumble.sourceforge.net
  %          Sed-script: booktolatex.sed
  % ------------------------------------------- 

  \documentclass[a4paper,12pt]{article} 
  \usepackage[margin=0.4cm,noheadfoot]{geometry} 
  \usepackage{color}                   %% to use colours, use "xcolor" for more
  \usepackage{multicol}                %% for multiple columns 
  \usepackage{keystroke}               %% for keyboard key images 
  \usepackage[toc]{multitoc}           %% for multi column table of contents
  \usepackage{tocloft}                 %% to customize the table of contents
  \setcounter{tocdepth}{2}             %% only display 2 levels in the contents
  \setlength{\cftbeforesecskip}{0cm}   %% make the toc more compact
  \usepackage{listings}                %% for nice code listings
  %\lstset{language={},
  \lstset{language=awk,                 
    %% define special comment delimiters '##(' and ')' 
    moredelim=[s][\color{grey}\itshape\footnotesize\ttfamily]{~(}{)},
    basicstyle=\ttfamily,           %% fixed pitch font
    xleftmargin=1cm,                %% margin on the left outside the frames
    breaklines=true,                %% break long code lines
    breakatwhitespace=false,        %% break long code lines anywhere
    breakindent=10pt,               %% reduce the indent from 20pt to 10
    postbreak=\mbox{{\color{blue}\small$\Rightarrow$\space}},  %% mark with arrow
    showstringspaces=false,            %% dont show spaces within strings 
    framerule=5pt,                     %% thickness of the frames
    rulecolor=\color{lightgrey}, frame=l}   %% source code settings
  \usepackage{graphicx}                %% to include images
  \usepackage{fancybox}                %% boxes with rounded corners 
  \usepackage{wrapfig}                 %% flow text around tables, images 
  \usepackage{tabularx}                %% change width of tables 
  \usepackage[table]{xcolor}           %% alternate row colour tables
  \usepackage{booktabs}                %% for heavier rules in tables 
  \usepackage[small,compact]{titlesec} %% sections more compact, less space
  \usepackage{enumitem}                %% more compact and better lists 
  \setlist{noitemsep}                  %% reduce list item spacing 
  \usepackage{hyperref}     %% make urls into hyperlinks
  \hypersetup{              %% add "pdftex," if only pdf output is required
     colorlinks=true,       %% set up the colours for the hyperlinks 
     linkcolor=black,       %% internal document links black 
     urlcolor=black,        %% url links black 
     filecolor=red,       
     citecolor=red, 
     bookmarks=true, pdfpagemode=UseOutlines} 

  % define some colours to use
  \definecolor{lightgrey}{gray}{0.70}
  \definecolor{grey}{gray}{0.30}

  \titleformat{\section}[frame]    %% titlesec: create framed section headings
     {\normalfont} 
     {\filleft \footnotesize \enspace Section \thesection\enspace\enspace} 
     {3pt} {\bfseries\itshape\filright} 
     
  \title{The Awk Text Processing Language} 
  \author{}
  \date{28 April 2015, 11:36pm} 
  \setlength{\parindent}{0pt}
  % \setlength{\parskip}{1ex}

  % label lists with stars
  \renewcommand{\labelitemi}{$\star$}

  \begin{document} 

  \centerline{\Large \bf The Awk Text Processing Language} \medskip
  \begin{center}
    {\huge ``}\textit{}{\huge ''}
    \textsc{}
  \end{center}
  % -----------------------------------
  % the toc should be 2 columns because of the \multitoc package 
  \tableofcontents



   
   Awk is a unix tool, or programming language designed to process and
   transform text files which are arranged in a series of 'fields'  (chunks
   of text separated by spaces, or any other delimiter) and records. This
   document is mainly about the 'mawk' variant of 'awk'.

\emph{ Find out the version of mawk }
\begin{lstlisting}
  mawk -W version
\end{lstlisting}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ helpful man pages for awk }} \\
  \hline

   \texttt{ man gawk } & The gnu awk man page \\ 

   \texttt{ man ed } & Contains regular expression examples \\ 

   \texttt{ man mawk } & Contains good examples \\ 

   \texttt{ man regex } & Regular expression syntax \\ 

    \hline
    \end{tabular}
    \end{center}
\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://sparky.rice.edu/awk.html}]
     more awk one liners
\end{description}

\section{Gotchas}

  [+] The so-called ``gotchas'' are small but potentially frustating
  problems which arise and which stop a program from working or which
  make the awk program work in an unexpected way.  Gotcha derives from
  the contraction of the english phrase ``got you''.

  \begin{itemize}
  \item 
     On a unix system the awk phrase $<$$<$awk ``$\{$print \$1$\}$''$>$$>$ doesnt work
     as expected because the unix (bash) shell expands or ``interpolates''
     the ``\$1'' variable. It is necessary to write ``awk '$\{$print \$1$\}$'''
    \item  
\end{itemize}
\emph{ BEGIN and and variables such as FS must be uppercase }
\begin{lstlisting}
  begin{FS=","}{print $2}    ~(No!! this doesnt work)
\end{lstlisting}

\section{Simple Usage}

\emph{ Simple usage of awk on different operating systems. }
  \begin{lstlisting}
     Unix: awk '/pattern/ {print "$1"}'    # standard Unix shells
  DOS/Win: awk '/pattern/ {print "$1"}'    # compiled with DJGPP, Cygwin
           awk "/pattern/ {print \"$1\"}"  # GnuWin32, UnxUtils, Mingw
  \end{lstlisting}

  Users of MS-DOS or Microsoft Windows must remember that the percent
  sign (\%) is used to indicate environment variables, so this symbol must
  be doubled (\%\%) to yield a single percent sign visible to awk.

\emph{ Run an awk script }
\begin{lstlisting}
  cat file1 | awk -f a.awk > file2
\end{lstlisting}
\begin{lstlisting}
  awk -f a.awk file1 > file2   ~(the same)
\end{lstlisting}

\section{Strings}

\subsection{Concatenation Of String}

  Concatenation is the fancy term for joining 2 strings (bits of text)
  together.

\emph{ Print the first two columns of the space/tab delimited file 'data.txt' }
\begin{lstlisting}
  awk '{print $1 $2}' data.txt  ~($1 and $2 are printed with no space between)
\end{lstlisting}
\begin{lstlisting}
  awk '{print $1$2}' data.txt    ~(the same, at least on my mawk version)
\end{lstlisting}
\begin{lstlisting}
  awk '{print $1 $2;}' data.txt    ~(the same again)
\end{lstlisting}
\begin{lstlisting}
  awk '{print $1 "" $2}' data.txt  ~(the same again, but why would you?)
\end{lstlisting}
  
\emph{ Awk doesnt have variable 'interpolation' in strings  }
\begin{lstlisting}
  awk '{print "$1 ..."}' data.txt   ~(this prints '$1 ...' literally)
\end{lstlisting}

\emph{ Print the first column of 'data.txt' with 3 dots '...' appended to it }
\begin{lstlisting}
  awk '{print $1 "..."}' data.txt
\end{lstlisting}

\emph{ Append a string to itself (string concatenation) }
\begin{lstlisting}
  s = s "xxx";  ~(this appends 3 x's to the end of the string 's')
\end{lstlisting}

\subsection{Matching Patterns}

\emph{ Determine if the variable "s`` contains the letter ''r" }
\begin{lstlisting}
  s ~ /r/
\end{lstlisting}

\emph{ Print the first field of each line if it does *not* contain "a`` or ''b"  }
\begin{lstlisting}
  $1 !~ /(a|b)/ { print $1 }
\end{lstlisting}
\begin{lstlisting}
  $1 !~ /[ab]/ { print $1 }     ~(the same)
\end{lstlisting}

\emph{ Add an "X" between every letter of every line }
\begin{lstlisting}
  { gsub(//, "X") ; print }
\end{lstlisting}

\emph{ Split the string "s" into the array A using the pattern "r" }
\begin{lstlisting}
  split(s, A, r)
\end{lstlisting}
 
\subsection{Printing Strings}

\emph{ Make a multiline string.. }
  \begin{lstlisting}
    print "\
     <html> \n\
     <head> \n\
    "
  \end{lstlisting}

\emph{ Print multiple expressions }
\begin{lstlisting}
  print "variable a is " a "."
\end{lstlisting}
  
\emph{ Its not possible to break printing expressions across lines }
  \begin{lstlisting}

    print "variable a is"
          a ".";
  \end{lstlisting}
  (this doesnt work, at least not with mawk  1.3.3)

\subsection{Newlines}

\emph{ Display the file 'days.txt' with all newline characters removed  }
\begin{lstlisting}
  awk '{ printf "%s", $0 }' days.txt
\end{lstlisting}
\begin{lstlisting}
  cat days.txt | awk '{ printf "%s", $0 }'  ~(the same)
\end{lstlisting}

\emph{ Display 'days.txt' with newline characters replaced with spaces }
\begin{lstlisting}
  awk '{ printf "%s ", $0 }' days.txt
\end{lstlisting}
\begin{lstlisting}
  cat days.txt | awk '{ printf "%s ", $0 }' 
\end{lstlisting}

\section{Arrays}
  
\emph{ Delete an array called record }
\begin{lstlisting}
  delete record
\end{lstlisting}

\emph{ Assign a value to an associative style array }
\begin{lstlisting}
  a["cars"] = 3
\end{lstlisting}

\section{Regular Expressions}

\emph{ Regular expression meta-characters: \^{} \$ . [ ] | ( ) * + ? }

\emph{ Print all lines which start with an awk identifier }
  \begin{lstlisting}
    BEGIN { identifier = "[_a-zA-Z][_a-zA-Z0-9]*" } 
    $0 ~ "^" identifier
  \end{lstlisting}

\subsection{Case Insensitive Matching}

\emph{ Use tolower }
\begin{lstlisting}
  tolower($0) ~ /bhp/ {print $0}
\end{lstlisting}

\emph{ Set the ignorecase var }
\begin{lstlisting}
  BEGIN {IGNORECASE=1} /bhp/ {print $0}
\end{lstlisting}

\section{Loops}
  
\emph{ Loop through each field of each record }
\begin{lstlisting}
  awk '{ for(i = 1 ; i <= NF ; i++)  print $i }' /usr/share/dict/words
\end{lstlisting}
  
\emph{ Print each element of an array }
\begin{lstlisting}
  for ( i in aa ) print aa[i]
\end{lstlisting}

\section{Splitting Data Fields}

   The field separator variable FS is interpreted as a regular 
   expression

\emph{ Split fields with any character followed by a colon ":" character }
\begin{lstlisting}
  BEGIN {FS=".:"}
\end{lstlisting}

\emph{ Split quoted comma delimited fields (csv) }
\begin{lstlisting}
  BEGIN {FS="\" *, *\""}
\end{lstlisting}


  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ awk built in variables }} \\
  \hline

   \texttt{ ARGC } & Number of command line arguments. \\ 

   \texttt{ ARGV } & Array of command line arguments, 0..ARGC-1. \\ 

   \texttt{ CONVFMT } & Format for conversion of numbers to string, default ``\%.6g''. \\ 

   \texttt{ ENVIRON } & Array indexed by environment variables.  An  environment string, var=value is stored as ENVIRON[var] = value. \\ 

   \texttt{ FILENAME } & Name of the current input file. \\ 

   \texttt{ FNR } & Current record number in FILENAME. \\ 

   \texttt{ FS } & Splits records into fields as a regular expression. \\ 

   \texttt{ NF } & Number of fields in the current record. \\ 

   \texttt{ NR } & Current record number in the total input stream. \\ 

   \texttt{ OFMT } & Format for printing numbers; initially = ``\%.6g''. \\ 

   \texttt{ OFS } & Inserted between fields on output, initially = " ". \\ 

   \texttt{ ORS } & Terminates each record on output, initially = ``\textbackslash n''. \\ 

   \texttt{ RLENGTH } & Length  set  by  the last call to the built-in function, match(). \\ 

   \texttt{ RS } & Input record separator, initially = ``\textbackslash n''. \\ 

   \texttt{ RSTART } & Index set by the last call to match(). \\ 

   \texttt{ SUBSEP } & Used to build multiple  array  subscripts,  initially  = ``\textbackslash 034''. \\ 

    \hline
    \end{tabular}
    \end{center}
\section{Range Of Fields}

  Awk has no simple way to print a range of fields such as \$[1-4]
  A 'for' loop must be used to loop through the range and print 
  each one. One may use cut instead

\emph{ Use 'cut' to print fields 1 to 5 from a comma delimited file }
\begin{lstlisting}
  cut -d, -f1-5
\end{lstlisting}

\section{Awk One Line Recipes}

 These one line scripts were taken from http://www.pement.org/awk/awk1line.txt

\emph{ 30 April 2008,  by Eric Pement - eric [at] pement.org, version 0.27 }

\begin{description}[labelindent=1cm, leftmargin=2cm, style=nextline]
 \item[\url{http://www.pement.org/awk/awk1line.txt}]
    Latest version of the Eric Pement one line scripts (in English) 
 \item[\url{http://ximix.org/translation/awk1line_zh-CN.txt}]   
    Chinese version of these one line scripts 
\end{description}

\section{File Spacing}

\emph{ Double space a file }
\begin{lstlisting}
  awk '1;{print ""}'
\end{lstlisting}
\begin{lstlisting}
  awk 'BEGIN{ORS="\n\n"};1'   ~(another way)
\end{lstlisting}

\emph{ Double space a file which already has blank lines in it. Output file }
\emph{ Should contain no more than one blank line between lines of text. }
\emph{ NOTE: On Unix systems, DOS lines which have only CRLF (\textbackslash r\textbackslash n) are }
\emph{ Often treated as non-blank, and thus 'NF' alone will return TRUE. }
\begin{lstlisting}
  awk 'NF{print $0 "\n"}'
\end{lstlisting}

\emph{ Triple space a file }
\begin{lstlisting}
  awk '1;{print "\n"}'
\end{lstlisting}

\section{Summing Numeric Columns}

\emph{ Sum up all the numbers in column 2 and print out the total at the end  }
\begin{lstlisting}
  awk '{ a+=$2 } END { print "total=" a }' data.txt
\end{lstlisting}

\emph{ Sum a column between 2 lines in a file (with help from sed) }
\begin{lstlisting}
  sed -n '/#1/,/#2/p' data.txt | awk -F, '{a+=$2; print $2, a}' | less
\end{lstlisting}

\section{Line Numbering}

\emph{ Precede each line by its line number FOR THAT FILE (left alignment). }
\emph{ Using a tab (\textbackslash t) instead of space will preserve margins. }
\begin{lstlisting}
  awk '{print FNR "\t" $0}' files*
\end{lstlisting}

\emph{ Precede each line by its line number FOR ALL FILES TOGETHER, with tab. }
\begin{lstlisting}
  awk '{print NR "\t" $0}' files*
\end{lstlisting}

\emph{ Number each line of a file (number on left, right-aligned) }
\emph{ Double the percent signs if typing from the DOS command prompt. }
\begin{lstlisting}
  awk '{printf("%5d : %s\n", NR,$0)}'
\end{lstlisting}

\emph{ Number each line of file, but only print numbers if line is not blank }
\emph{ Remember caveats about Unix treatment of \textbackslash r (mentioned above) }
\begin{lstlisting}
  awk 'NF{$0=++a " :" $0};1'
\end{lstlisting}
\begin{lstlisting}
  awk '{print (NF? ++a " :" :"") $0}'
\end{lstlisting}

\emph{ Count lines (emulates ``wc -l'') }
\begin{lstlisting}
  awk 'END{print NR}'
\end{lstlisting}

\emph{ Print the sums of the fields of every line }
\begin{lstlisting}
  awk '{s=0; for (i=1; i<=NF; i++) s=s+$i; print s}'
\end{lstlisting}

\emph{ Add all fields in all lines and print the sum }
\begin{lstlisting}
  awk '{for (i=1; i<=NF; i++) s=s+$i}; END{print s}'
\end{lstlisting}

\emph{ Print every line after replacing each field with its absolute value }
\begin{lstlisting}
  awk '{for (i=1; i<=NF; i++) if ($i < 0) $i = -$i; print }'
\end{lstlisting}
\begin{lstlisting}
  awk '{for (i=1; i<=NF; i++) $i = ($i < 0) ? -$i : $i; print }'
\end{lstlisting}

\emph{ Print the total number of fields (``words'') in all lines }
\begin{lstlisting}
  awk '{ total = total + NF }; END {print total}' file
\end{lstlisting}

\emph{ Print the total number of lines that contain ``Beth'' }
\begin{lstlisting}
  awk '/Beth/{n++}; END {print n+0}' file
\end{lstlisting}

\emph{ Print the largest first field and the line that contains it }
\emph{ Intended for finding the longest string in field \#1 }
\begin{lstlisting}
  awk '$1 > max {max=$1; maxline=$0}; END{ print max, maxline}'
\end{lstlisting}

\section{The Number Of Fields}

\emph{ Print the number of fields in each line, followed by the line }
\begin{lstlisting}
  awk '{ print NF ":" $0 } '
\end{lstlisting}

\emph{ Print the last field of each line }
\begin{lstlisting}
  awk '{ print $NF }'
\end{lstlisting}

\emph{ Print the last field of the last line }
\begin{lstlisting}
  awk '{ field = $NF }; END{ print field }'
\end{lstlisting}

\emph{ Print every line with more than 4 fields }
\begin{lstlisting}
  awk 'NF > 4'
\end{lstlisting}

\emph{ Print every line where the value of the last field is $>$ 4 }
\begin{lstlisting}
  awk '$NF > 4'
\end{lstlisting}

\section{String Creation}

\emph{ Create a string of a specific length (e.g., generate 513 spaces) }
\begin{lstlisting}
  awk 'BEGIN{while (a++<513) s=s " "; print s}'
\end{lstlisting}

\emph{ Insert a string of specific length at a certain character position }
\emph{ Example: insert 49 spaces after column \#6 of each input line. }
 gawk --re-interval 'BEGIN$\{$while(a++$<$49)s=s " ``$\}$;$\{$sub(/\^{}.$\{$6$\}$/,''\&" s)$\}$;1'

\section{Array Creation}

\emph{ These next 2 entries are not one-line scripts, but the technique }
\emph{ Is so handy that it merits inclusion here. }
 
\emph{ Create an array named ``month'', indexed by numbers, so that month[1] }
\emph{ Is 'Jan', month[2] is 'Feb', month[3] is 'Mar' and so on. }
\begin{lstlisting}
  split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", month, " ")
\end{lstlisting}

\emph{ Create an array named ``mdigit'', indexed by strings, so that }
\emph{ Mdigit[``Jan''] is 1, mdigit[``Feb''] is 2, etc. Requires ``month'' array }
\begin{lstlisting}
  for (i=1; i<=12; i++) mdigit[month[i]] = i
\end{lstlisting}

\section{Text Conversion And Substitution}

\emph{ IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format }
\begin{lstlisting}
  awk '{sub(/\r$/,"")};1'   # assumes EACH line ends with Ctrl-M
\end{lstlisting}

\emph{ IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format }
\begin{lstlisting}
  awk '{sub(/$/,"\r")};1'
\end{lstlisting}

\emph{ IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format }
\begin{lstlisting}
  awk 1
\end{lstlisting}

\emph{ IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format }
\emph{ Cannot be done with DOS versions of awk, other than gawk }
\begin{lstlisting}
  gawk -v BINMODE="w" '1' infile >outfile
\end{lstlisting}

\emph{ Use ``tr'' instead. }
\begin{lstlisting}
  tr -d \r <infile >outfile        ~( GNU tr version 1.22 or higher )
\end{lstlisting}

\emph{ Delete leading whitespace (spaces, tabs) from front of each line }
\begin{lstlisting}
  awk '{sub(/^[ \t]+/, "")};1'     ~(aligns all text flush left)
\end{lstlisting}

\emph{ Delete trailing whitespace (spaces, tabs) from end of each line }
\begin{lstlisting}
  awk '{sub(/[ \t]+$/, "")};1'
\end{lstlisting}

\emph{ Delete BOTH leading and trailing whitespace from each line }
\begin{lstlisting}
  awk '{gsub(/^[ \t]+|[ \t]+$/,"")};1'
\end{lstlisting}
\begin{lstlisting}
  awk '{$1=$1};1'           # also removes extra space between fields
\end{lstlisting}

\emph{ Insert 5 blank spaces at beginning of each line (make page offset) }
\begin{lstlisting}
  awk '{sub(/^/, "     ")};1'
\end{lstlisting}

\emph{ Align all text flush right on a 79-column width }
\begin{lstlisting}
  awk '{printf "%79s\n", $0}' file*
\end{lstlisting}

\emph{ Center all text on a 79-character width }
\begin{lstlisting}
  awk '{l=length();s=int((79-l)/2); printf "%"(s+l)"s\n",$0}' file*
\end{lstlisting}

\emph{ Substitute (find and replace) ``foo'' with ``bar'' on each line }
\begin{lstlisting}
  awk '{sub(/foo/,"bar")}; 1'           # replace only 1st instance
\end{lstlisting}
\begin{lstlisting}
  gawk '{$0=gensub(/foo/,"bar",4)}; 1'  # replace only 4th instance
\end{lstlisting}
\begin{lstlisting}
  awk '{gsub(/foo/,"bar")}; 1'          # replace ALL instances in a line
\end{lstlisting}

\emph{ Substitute ``foo'' with ``bar'' ONLY for lines which contain ``baz'' }
\begin{lstlisting}
  awk '/baz/{gsub(/foo/, "bar")}; 1'
\end{lstlisting}

\emph{ Substitute ``foo'' with ``bar'' EXCEPT for lines which contain ``baz'' }
\begin{lstlisting}
  awk '!/baz/{gsub(/foo/, "bar")}; 1'
\end{lstlisting}

\emph{ Change ``scarlet'' or ``ruby'' or ``puce'' to ``red'' }
\begin{lstlisting}
  awk '{gsub(/scarlet|ruby|puce/, "red")}; 1'
\end{lstlisting}

\emph{ Reverse order of lines (emulates ``tac'') }
\begin{lstlisting}
  awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*
\end{lstlisting}

\emph{ If a line ends with a backslash, append the next line to it (fails if }
\emph{ There are multiple lines ending with backslash...) }
\begin{lstlisting}
  awk '/\\$/ {sub(/\\$/,""); getline t; print $0 t; next}; 1' file*
\end{lstlisting}

\emph{ Print and sort the login names of all users }
\begin{lstlisting}
  awk -F ":" '{print $1 | "sort" }' /etc/passwd
\end{lstlisting}

\section{Rearranging Fields Or Columns}

\emph{ Print the first 2 fields, in opposite order, of every line }
\begin{lstlisting}
  awk '{print $2, $1}' file
\end{lstlisting}

\emph{ Switch the first 2 fields of every line }
\begin{lstlisting}
  awk '{temp = $1; $1 = $2; $2 = temp}' file
\end{lstlisting}

\emph{ Print every line, deleting the second field of that line }
\begin{lstlisting}
  awk '{ $2 = ""; print }'
\end{lstlisting}

\emph{ Print in reverse order the fields of every line }
\begin{lstlisting}
  awk '{for (i=NF; i>0; i--) printf("%s ",$i);print ""}' file
\end{lstlisting}

\emph{ Concatenate every 5 lines of input, using a comma separator between fields }
\begin{lstlisting}
  awk 'ORS=NR%5?",":"\n"' file
\end{lstlisting}

\section{Selective Printing Of Certain Lines}

\emph{ Print first 10 lines of file (emulates behavior of ``head'') }
\begin{lstlisting}
  awk 'NR < 11'
\end{lstlisting}

\emph{ Print first line of file (emulates ``head -1'') }
\begin{lstlisting}
  awk 'NR>1{exit};1'
\end{lstlisting}

\emph{ Print the last 2 lines of a file (emulates ``tail -2'') }
\begin{lstlisting}
  awk '{y=x "\n" $0; x=$0};END{print y}'
\end{lstlisting}

\emph{ Print the last line of a file (emulates ``tail -1'') }
\begin{lstlisting}
  awk 'END{print}'
\end{lstlisting}

\emph{ Print only lines which match regular expression (emulates ``grep'') }
\begin{lstlisting}
  awk '/regex/'
\end{lstlisting}

\emph{ Print only lines which do NOT match regex (emulates ``grep -v'') }
\begin{lstlisting}
  awk '!/regex/'
\end{lstlisting}

\emph{ Print any line where field \#5 is equal to ``abc123'' }
\begin{lstlisting}
  awk '$5 == "abc123"'
\end{lstlisting}

\emph{ Print only those lines where field \#5 is NOT equal to ``abc123'' }
\emph{ This will also print lines which have less than 5 fields. }
\begin{lstlisting}
  awk '$5 != "abc123"'
\end{lstlisting}
\begin{lstlisting}
  awk '!($5 == "abc123")'
\end{lstlisting}

\emph{ Matching a field against a regular expression }
\begin{lstlisting}
  awk '$7  ~ /^[a-f]/'    # print line if field #7 matches regex
\end{lstlisting}
\begin{lstlisting}
  awk '$7 !~ /^[a-f]/'    # print line if field #7 does NOT match regex
\end{lstlisting}

\emph{ Print the line immediately before a regex, but not the line }
\emph{ Containing the regex }
\begin{lstlisting}
  awk '/regex/{print x};{x=$0}'
\end{lstlisting}
\begin{lstlisting}
  awk '/regex/{print (NR==1 ? "match on line 1" : x)};{x=$0}'
\end{lstlisting}

\emph{ Print the line immediately after a regex, but not the line }
\emph{ Containing the regex }
\begin{lstlisting}
  awk '/regex/{getline;print}'
\end{lstlisting}

\emph{ Grep for AAA and BBB and CCC (in any order on the same line) }
\begin{lstlisting}
  awk '/AAA/ && /BBB/ && /CCC/'
\end{lstlisting}

\emph{ Grep for AAA and BBB and CCC (in that order) }
\begin{lstlisting}
  awk '/AAA.*BBB.*CCC/'
\end{lstlisting}

\emph{ Print only lines of 65 characters or longer }
\begin{lstlisting}
  awk 'length > 64'
\end{lstlisting}

\emph{ Print only lines of less than 65 characters }
\begin{lstlisting}
  awk 'length < 64'
\end{lstlisting}

\emph{ Print section of file from regular expression to end of file }
\begin{lstlisting}
  awk '/regex/,0'
\end{lstlisting}
\begin{lstlisting}
  awk '/regex/,EOF'
\end{lstlisting}

\emph{ Print section of file based on line numbers (lines 8-12, inclusive) }
\begin{lstlisting}
  awk 'NR==8,NR==12'
\end{lstlisting}

\emph{ Print line number 52 }
\begin{lstlisting}
  awk 'NR==52'
\end{lstlisting}
\begin{lstlisting}
  awk 'NR==52 {print;exit}'          # more efficient on large files
\end{lstlisting}

\emph{ Print section of file between two regular expressions (inclusive) }
\begin{lstlisting}
  awk '/Iowa/,/Montana/'             # case sensitive
\end{lstlisting}

\section{Selective Deletion Of Certain Lines}

\emph{ Delete ALL blank lines from a file (same as ``grep '.' '') }
\begin{lstlisting}
  awk NF
\end{lstlisting}
\begin{lstlisting}
  awk '/./'
\end{lstlisting}

\emph{ Remove duplicate, consecutive lines (emulates ``uniq'') }
\begin{lstlisting}
  awk 'a !~ $0; {a=$0}'
\end{lstlisting}

\emph{ Remove duplicate, nonconsecutive lines }
\begin{lstlisting}
  awk '!a[$0]++'                     # most concise script
\end{lstlisting}
\begin{lstlisting}
  awk '!($0 in a){a[$0];print}'      # most efficient script
\end{lstlisting}

\section{Pipe Awk Output To The Shell}

 This technique allows each line generated by an awk script
 to be executed by the shell

\emph{ Move files to the ``iraf'' folder and add .dat to the names }
\begin{lstlisting}
  ls junk* | awk '{print "mv "$0" ../iraf/"$0".dat"}' | sh
\end{lstlisting}

\section{More One Line Examples}

\emph{ Print first two fields in opposite order }
\begin{lstlisting}
  awk '{ print $2, $1 }' file
\end{lstlisting}

\emph{ Print lines longer than 72 characters }
\begin{lstlisting}
  awk 'length > 72' file
\end{lstlisting}

\emph{ Print length of string in 2nd column }
\begin{lstlisting}
  awk '{print length($2)}' file
\end{lstlisting}

\emph{ Add up first column, print sum and average }
\begin{lstlisting}
  { s += $1 }
\end{lstlisting}
\begin{lstlisting}
  END  { print "sum is", s, " average is", s/NR }
\end{lstlisting}

\emph{ Print fields in reverse order }
\begin{lstlisting}
  awk '{ for (i = NF; i > 0; --i) print $i }' file
\end{lstlisting}

\emph{ Print the last line }
\begin{lstlisting}
  {line = $0}
\end{lstlisting}
\begin{lstlisting}
  END {print line}
\end{lstlisting}

\emph{ Print the total number of lines that contain the word Pat }
\begin{lstlisting}
  /Pat/ {nlines = nlines + 1}
\end{lstlisting}
\begin{lstlisting}
  END {print nlines}
\end{lstlisting}

\emph{ Print all lines between start/stop pairs }
\begin{lstlisting}
  awk '/start/, /stop/' file
\end{lstlisting}

\emph{ Print all lines whose first field is different from previous one }
\begin{lstlisting}
  awk '$1 != prev { print; prev = $1 }' file
\end{lstlisting}

\emph{ Print column 3 if column 1 $>$ column 2 }
\begin{lstlisting}
  awk '$1 > $2 {print $3}' file
\end{lstlisting}

\emph{ Print line if column 3 $>$ column 2 }
\begin{lstlisting}
  awk '$3 > $2' file
\end{lstlisting}

\emph{ Count number of lines where col 3 $>$ col 1 }
\begin{lstlisting}
  awk '$3 > $1 {print i + "1"; i++}' file
\end{lstlisting}

\emph{ Print sequence number and then column 1 of file }
\begin{lstlisting}
  awk '{print NR, $1}' file
\end{lstlisting}

\emph{ Print every line after erasing the 2nd field }
\begin{lstlisting}
  awk '{$2 = ""; print}' file
\end{lstlisting}

\emph{ Print hi 28 times }
\begin{lstlisting}
  yes | head -28 | awk '{ print "hi" }'
\end{lstlisting}

\emph{ Print hi.0010 to hi.0099 (NOTE IRAF USERS!) }
\begin{lstlisting}
  yes | head -90 | awk '{printf("hi00%2.0f \n", NR+9)}'
\end{lstlisting}

\emph{ Print out 4 random numbers between 0 and 1 }
\begin{lstlisting}
  yes | head -4 | awk '{print rand()}'
\end{lstlisting}

\emph{ Print out 40 random integers modulo 5 }
\begin{lstlisting}
  yes | head -40 | awk '{print int(100*rand()) % 5}'
\end{lstlisting}

\emph{ Replace every field by its absolute value }
\begin{lstlisting}
  { for (i = 1; i <= NF; i=i+1) if ($i < 0) $i = -$i print}
\end{lstlisting}

\section{Field Delimiter}

 The field delimiter or separator, determines how awk divides up each
 line of the text file into 'fields' or 'columns' which can then be
 accessed with the \$1, \$2, ... variables. The delimiter can be a
 regular expression (unlike 'cut' for example)

 The default awk field delimiter is a single space " " or a tab.

\emph{ Use '|' as the field delimiter and print the 4th field }
\begin{lstlisting}
  awk -F"|" '{print $4}' filename
\end{lstlisting}
\begin{lstlisting}
  awk -F'|' '{print $4}' filename           ~(the same)
\end{lstlisting}
\begin{lstlisting}
  awk -F\| '{print $4}' filename            ~(should work)
\end{lstlisting}
\begin{lstlisting}
  awk  'BEGIN {FS="|"} {print $4}' filename ~(the same)
\end{lstlisting}

\emph{ Set the field delimiter to be a comma followed by a space, print 2nd field }
\begin{lstlisting}
  awk -F', ' '{print $2}' data.txt
\end{lstlisting}

\emph{ Set the field delimiter to be a comma followed by any number of spaces  }
\begin{lstlisting}
  awk -F', *' '{print $2}' data.txt 
\end{lstlisting}
\begin{lstlisting}
  awk 'BEGIN{FS=", *"}{print $2}' data.txt     ~(the same)
\end{lstlisting}
\begin{lstlisting}
  awk 'BEGIN{FS=", *";};{print $2;}' data.txt  ~(the same again)
\end{lstlisting}

\emph{ Set the field delimiter to be the double quote character }
\begin{lstlisting}
  awk -F'"' '{print $2}' data.txt
\end{lstlisting}
\begin{lstlisting}
  awk -F\" '{print $2}' data.txt    ~(the same)
\end{lstlisting}

\emph{ Set the field delimiter to be any number of '+' plus signs }
\begin{lstlisting}
  awk -F'\+*' '{print $2}' data.txt
\end{lstlisting}

\emph{ Set the field delimiter to a space following by one or more '*' star signs }
\begin{lstlisting}
  awk -F' \*+' '{print $2}' data.txt
\end{lstlisting}

\emph{ Some looping commands Remove a bunch of print jobs from the queue }
 \begin{lstlisting}

   BEGIN{
       for (i=875;i>833;i--){
                printf "lprm -Plw %d\n", i
        } exit
       }
  \end{lstlisting}



  \arrayrulecolor{gray}
  \begin{center}
  \begin{tabular}{ |rl| }
    \multicolumn{2}{c}{\textbf{ example format strings for 'printf' }} \\
  \hline

 \texttt{ e.g. printf("howdy \%-8s What it is bro. \%.2f\textbackslash n" } & \$1, \$2*\$3) \\ 

 \texttt{ \%s } & String \\ 

 \texttt{ \%-8s } & 8 character string left justified \\ 

 \texttt{ \%.2f } & Number with 2 places after . \\ 

 \texttt{ \%6.2f } & Field 6 chars with 2 chars after . \\ 

 \texttt{ \textbackslash n } & Newline \\ 

 \texttt{ \textbackslash t } & Tab \\ 

    \hline
    \end{tabular}
    \end{center}
\emph{ Find maximum and minimum values present in column 1 }
 \begin{lstlisting}
   NR == 1 {m=$1 ; p=$1}
   $1 >= m {m = $1}
   $1 <= p {p = $1}
   END { print "Max = " m, "   Min = " p }
 \end{lstlisting}

\emph{ Example of defining variables, multiple commands on one line }
 \begin{lstlisting}

   NR == 1 {prev=$4; preva = $1; prevb = $2; n=0; sum=0}
   $4 != prev {print preva, prevb, prev, sum/n; n=0; sum=0; prev = $4; preva = $1;
    prevb = $2}
   $4 == prev {n++; sum=sum+$5/$6}
   END {print preva, prevb, prev, sum/n}
 \end{lstlisting}

\emph{ Example of defining and using a function, inserting values into an array }
\emph{ And doing integer arithmetic mod(n). This script finds the number of days }
\emph{ Elapsed since Jan 1, 1901. (from http://www.netlib.org/research/awkbookcode/c }
 \begin{lstlisting}

   h3)
   function daynum(y, m, d,    days, i, n)
   {   # 1 == Jan 1, 1901
       split("31 28 31 30 31 30 31 31 30 31 30 31", days)
       # 365 days a year, plus one for each leap year
       n = (y-1901) * 365 + int((y-1901)/4)
       if (y % 4 == 0) # leap year from 1901 to 2099
           days[2]++
       for (i = 1; i < m; i++)
           n += days[i]
       return n + d
   }
       { print daynum($1, $2, $3) }
 \end{lstlisting}

\emph{ Example of using substrings }
\emph{ Substr(\$2,9,7) picks out characters 9 thru 15 of column 2 }
 \begin{lstlisting}

  {print "imarith", substr($2,1,7) " - " $3, "out."substr($2,5,3)}
  {print "imarith", substr($2,9,7) " - " $3, "out."substr($2,13,3)}
  {print "imarith", substr($2,17,7) " - " $3, "out."substr($2,21,3)}
  {print "imarith", substr($2,25,7) " - " $3, "out."substr($2,29,3)}
 \end{lstlisting}

\section{Password Generation With Awk}

  A useful capability of awk may be in the generation of password
  'dictionary' files, for the use with security auditing programs
  ('password crackers') such as ``john'' and ``aircrack-ng''. Awk may be
  used to amplify and multiplex a text password dictionary file.

\emph{ Print each line joining to the preceding line }
\begin{lstlisting}
  awk '{print last$0; last=$0}' /usr/share/dict/words | less
\end{lstlisting}

\emph{ As above but with all punctuation removed }
\begin{lstlisting}
  awk '{gsub(/[[:punct:]]/,"");print last$0; last=$0}' /usr/share/dict/words | less
\end{lstlisting}

\section{Software Written With Awk}

  http://www.soimort.org/translate-shell/
    a very good command line script to access Google translate

\section{Alternatives To Awk}

  awk is particularly good handling 'csv' (comma separated
  values) data or other tabular style data.

  cut -
  perl - 
  sed -

\section{Books About Awk}

  ``sed \& awk, 2nd Edition,'' by Dale Dougherty and Arnold Robbins
  (O'Reilly, 1997)

  ``UNIX Text Processing,'' by Dale Dougherty and Tim O'Reilly (Hayden
  Books, 1987)

  "GAWK: Effective awk Programming," 3d edition, by Arnold D. Robbins
  (O'Reilly, 2003) or at http://www.gnu.org/software/gawk/manual/

  "Mastering Regular Expressions, 3d edition" by Jeffrey Friedl (O'Reilly, 2006).

  The info and manual (``man'') pages on Unix systems may be helpful (try
  ``man awk'', ``man nawk'', ``man gawk'', ``man regexp'', or the section on
  regular expressions in ``man ed'').

\section{Awk Contributors}

  Peter S. Tillier (U.K.); Daniel Jana; Yisu Dong

\section{History}

  Awk was created by Aho, W? and Kernighan. Mr Aho has written
  some dense books about computer science. Brian Kernighan has been
  an important figure in the early development of Unix. Kernighan
  co-authored the first 'c' book- the C programming language, he also
  has maintained nroff (used for man pages) as well as other obscure
  unix tools.

\section{Notes}

 
\emph{ Convert numbers to SI notation }
\begin{lstlisting}
  $ awk '{ split(sprintf("%1.3e", $1), b, "e"); p = substr("yzafpnum_kMGTPEZY", (b[2]/3)+9, 1); o = sprintf("%f", b[1] * (10 ^ (b[2]%3))); gsub(/\./, p, o); print substr( gensub(/_[[:digit:]]*/, "", "g", o), 1, 4); }' < test.dat
\end{lstlisting}

   \end{document}
