githubEdit

Text Swordsman

Text processing CLI references for awk, grep, and sed

awk

Basic Syntax

awk [POSIX or GNU style options] -f progfile [--] file
POSIX options:          GNU long options: (standard)
        -f progfile             --file=progfile
        -F fs                   --field-separator=fs
        -v var=val              --assign=var=val

-F fs          # fs specifies the input field separator, can be a string or regex, e.g. -F:
-v var=val     # assign a user-defined variable, pass external variables to awk
-f progfile    # read awk commands from a script file


# example
awk -F':' '{print $1}' /etc/passwd
awk 'BEGIN { print "Don\47t Panic!" }'


# run awk program, print the first column of each input line
awk '{print $1}'


# execute awk from file
cat > demo.awk << "EOF"
#! /bin/awk -f
BEGIN { print "Don't Panic!" }
EOF
# run
awk -f demo.awk top.txt
chmod +x demo.awk && ./demo.awk

Variables

Variable
Description

ARGC

Number of command-line arguments

ARGIND

Index of the current file in the command line (starts from 0)

ARGV

Array containing command-line arguments

CONVFMT

Number conversion format (default: %.6g)

ENVIRON

Associative array of environment variables

ERRNO

Description of the last system error

FIELDWIDTHS

Field width list (space-separated)

FILENAME

Name of the current input file

FNR

Same as NR, but relative to the current file

FS

Field separator (default: any whitespace)

IGNORECASE

If true, perform case-insensitive matching

NF

Number of fields in the current record

NR

Number of records processed (current line number)

OFMT

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

OFS

Output field separator (default: a space)

ORS

Output record separator (default: a newline)

RS

Record separator (default: a newline)

RSTART

Start position of the string matched by match()

RLENGTH

Length of the string matched by match()

SUBSEP

Array subscript separator (default: \034)

Functions & Conditions

Common Usage

grep

Basic Syntax

Common Usage

sed

Basic Syntax

Common Usage

Reference:

Last updated