awk

Find and Replace text within file(s)
Pattern-directed scanning and processing language.

Syntax
      awk  [ -F fs ] [ -v var=value ] [ 'prog' | -f progfile ] [ file ...  ]

Options

   -F fs        Define the input field separator = regular expression fs.

   -v var=value Assign values before prog is executed,
                any number of -v options can be present. 

   -f progfile  Specify a pattern to match within progfile
                rather then on the command line.

   -mr          Set the maximum size of the input record (MaxRows)

   -mf          Set the maximum number of fields (MaxFields)

The basic function of awk is to search files for lines (or other units of text) that contain a pattern.
When a line matches, awk performs a specific action on that line.

Suppose we have a file in which each line is a name followed by a phone number. Let’s say the file contains the line "Audrey 5550164."
In AWK, the first field is referred to as $1, the second as $2 and so on.
So an AWK program to retrieve Audrey’s phone number is:
awk '$1 == "Audrey" {print $2}' numbers.txt
which means if the first field matches Audrey, then print the second field.

In awk, $0 is the whole line of arguments.

Awk scans each input file for lines that match any of a set of patterns specified literally in prog or in one or more files specified as -f progfile. With each pattern there can be an associated action that will be performed when a line of a file matches the pattern.

Each line is matched against the pattern portion of every pattern-action statement; the associated action is performed for each matched pattern.

The file name - means the standard input.

Any file of the form var=value is treated as an assignment, not a filename, and is executed at the time it would have been opened if it were a filename.

An input line is normally made up of fields separated by white space, or by regular expression FS. The fields are denoted $1, $2, ..., while $0 refers to the entire line. If FS is null, the input line is split into one field per character. To compensate for inadequate implementation of storage management, the -mr option can be used to set the maximum size of the input record, and the -mf option to set the maximum number of fields.

A pattern-action statement has the form pattern { action }

A missing { action } means print the line; a missing pattern always matches.
Pattern-action statements are separated by newlines or semicolons.

An action is a sequence of statements. A statement can be one of the following:

   if( expression ) statement [ else statement ]

   while( expression ) statement

   for( expression ; expression ; expression ) statement

   for( var in array ) statement

   do statement while( expression )

   break
   continue

   { [ statement ... ] }

   expression              # commonly var = expression

   print [ expression-list ] [ > expression ]
   printf format [ , expression-list ] [ > expression ]

   next                    # skip remaining patterns on this input line

   nextfile                # skip rest of this file, open next, start at top

   delete array[ expression ]  # delete an array element
   delete array            # delete all elements of array
   exit [ expression ]     # exit immediately; status is expression

Statements are terminated by semicolons, newlines or right braces. An empty expression-list stands for $0. String constants are quoted " ", with the usual C escapes recognized within. Expressions take on string or numeric values as appropriate, and are built using the operators + - * / % ^ (exponentiation), and concatenation (indicated by white space).

The operators ! ++ -- += -= *= /= %= ^= >>= < <= == != ?: are also available in expressions. Variables can be scalars, array elements (denoted x[i]) or fields. Variables are initialized to the null string. Array subscripts can be any string, not necessarily numeric; this allows for a form of associative memory.
Multiple subscripts such as [i,j,k] are permitted; the constituents are concatenated, separated by the value of SUBSEP.

The print statement prints its arguments on the standard output (or on a file if >file or >>file is present or on a pipe if |cmd is present), separated by the current output field separator, and terminated by the output record separator. file and cmd can be literal names or parenthesized expressions; identical string values in different statements denote the same open file. The printf statement formats its expression list according to the format (see printf). The built-in function close(expr) closes the file or pipe expr. The built-in function fflush(expr)flushes any buffered output for the file or pipe expr.

       The mathematical functions exp, log, sqrt, sin,  cos,  and
       atan2 are built in.  Other built-in functions:

       length the length of its argument taken as a string, or of
              $0 if no argument.

       rand   random number on (0,1)

       srand  sets seed for rand and returns the previous seed.

       int    truncates to an integer value

       substr(s, m, n)
              the n-character substring of s that begins at posi-
              tion m counted from 1.

       index(s, t)
              the  position  in s where the string t occurs, or 0
              if it does not.

       match(s, r)
              the position in s where the  regular  expression  r
              occurs,  or 0 if it does not.  The variables RSTART
              and RLENGTH are set to the position and  length  of
              the matched string.

       split(s, a, fs)
              splits the string s into array elements a[1], a[2],
              ..., a[n], and returns n.  The separation  is  done
              with  the  regular  expression fs or with the field
              separator FS if fs is not given.  An  empty  string
              as field separator splits the string into one array
              element per character.

       sub(r, t, s)
              substitutes t for the first occurrence of the regu-
              lar  expression  r  in  the  string s.  If s is not
              given, $0 is used.

       gsub   same as sub except that all occurrences of the reg-
              ular  expression  are replaced; sub and gsub return
              the number of replacements.

       sprintf(fmt, expr, ... )
              the  string  resulting  from  formatting  expr  ...
              according to the printf(3) format fmt

       system(cmd)
              executes cmd and returns its exit status

       tolower(str)
              returns a copy of str with all upper-case characters
              translated to their corresponding lower-case equivalents.

       toupper(str)
              returns a copy of str with all lower-case characters
              translated to their corresponding upper-case equivalents.

The 'function' getline sets $0 to the next input record from the current input file; getline <file sets $0 to the next record from file. getline x sets variable x instead.
Finally, cmd | getline pipes the output of cmd into getline; each call of getline returns the next line of output from cmd.
In all cases, getline returns 1 for a successful input, 0 for end of file, and -1 for an error.

Patterns are arbitrary Boolean combinations (with ! || &&) of regular expressions and relational expressions. Regular expressions are as in egrep; see grep.

Isolated regular expressions in a pattern apply to the entire line. Regular expressions can also be used as a regular expression, except in the position of an isolated regular expression in a pattern.


A pattern can consist of two patterns separated by a comma; in this case, the action is performed for all lines from an occurrence of the first pattern though an occurrence of the second.

A relational expression is one of the following:

              expression matchop regular-expression
              expression relop expression
              expression in array-name
              (expr,expr,...) in array-name

Where a relop is any of the six relational operators in C, and a matchop is either ~ (matches) or !~ (does not match). A conditional is an arithmetic expression, a relational expression, or a Boolean combination of these.

The special patterns BEGIN and END can be used to capture control before the first input line is read and after the last.
BEGIN and END do not combine with other patterns.

Variable names with special meanings:

     CONVFMT  Conversion  format  used  when  converting  numbers
              (default %.6g)

     FS       Regular  expression  used  to separate fields; also
              settable by option -Ffs.

     NF       Number of fields in the current record

     NR       Ordinal number of the current record

     FNR      Ordinal number of the current record in the current
              file

     FILENAME The name of the current input file

     RS       Input record separator (default newline)

     OFS      Output field separator (default blank)

     ORS      Output record separator (default newline)

     OFMT     Output format for numbers (default %.6g)

     SUBSEP   separates multiple subscripts (default 034)

     ARGC     Argument count, assignable

     ARGV     Argument  array,  assignable;  non-null members are
              taken as filenames

     ENVIRON  Array of environment variables; subscripts  are names.

Examples

Print the Row Number (NR), then a dash and space ("- ") and then the first item ($1) from each line in samplefile.txt:

$ awk '{print NR "- " $1 }' samplefile.txt

Print the first item ($1) and then the third last item $(NF-2) from each line in samplefile.txt:

$ awk '{print $1, $(NF-2) }' samplefile.txt

Comparison with grep:

Using grep Dec against the following file listing would return all 3 rows as it matches text in different places:

-rw-r--r-- 7 simon simon 12043 31 Jan 2010 09:36 December.pdf
-rw-r--r-- 3 simon simon 1024 01 Dec 2010 11:59 README
-rw-r--r-- 3 simon simon 5096 14 Nov 2010 18:22 Decision.txt

Running awk '$7 == "Dec"'against the same file listing, $7 matches the exact field (column 7 = Month) so it will list only the December file:

$ ls -l /tmp/demo | awk '$7 == "Dec"'

Print lines longer than 72 characters:

length($0) > 72

Print first two fields in opposite order:

{ print $2, $1 }

Same, with input fields separated by comma and/or blanks and tabs:

BEGIN { FS = ",[ \t]*|[ \t]+" }
{ print $2, $1 }

Add up first column, print sum and average:

{ s += $1 }
END { print "sum is", s, " average is", s/NR }

Print all lines between start/stop pairs:

/start/, /stop/

BEGIN { # Simulate echo(1)
for (i = 1; i < ARGC; i++) printf "%s ", ARGV[i]
printf "\n"
exit }

“When the Last of the Great Auks Died, It Was by the Crush of a Fisherman’s Boot” ~ Samantha Galasso (Smithsonian)

Related macOS commands

AWK Help page - Brian Kernighan.
AWK tutorial and introduction - Bruce Barnett.
GNU Awk User Guide - Full guide with examples.
Learn By Example - AWK text processing.
Patrick Hartigan - How to use awk.
Gregable - Why you should know just a little Awk.
awk one liners - Eric Pement.
awk one liners explained & pt2 - Peteris Krumin (CatOnMat.net)

expr - Evaluate expressions.
for - Loop, expand words, and execute commands.
grep - Search file(s) for lines that match a given pattern.
tr - Translate, squeeze, and/or delete characters.
Equivalent Windows command: FOR - Conditionally perform a command several times.


 
Copyright © 1999-2024 SS64.com
Some rights reserved