Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linux awk Command

Linux awk Command

Linux Command Reference Linux Command Reference

awk is a language for processing text files and a powerful text analysis tool.

awk can read text files line by line and provides programming-language-like features, such as:

These features make AWK very efficient when processing structured text such as CSV and log files.

It is called awk because its name takes the first letters of the family names of its three founders: Alfred Aho, Peter Weinberger, and Brian Kernighan.

Syntax



awk options 'pattern {action}' file

Description of options and parameters:

Description of the options parameter:

Here are some common awk command usages:

Print the entire line:

awk '{print}' file

Print specific columns:



awk '{print $1, $2}' file

Specify columns using a separator:



awk -F',' '{print $1, $2}' file

Print the line count:



awk '{print NR, $0}' file

Print lines whose line count meets a condition:



awk '/pattern/ {print NR, $0}' file

Calculate the sum of a column:



awk '{sum += $1} END {print sum}' file

Print the maximum value:



awk 'max < $1 {max = $1} END {print max}' file

Formatted output:



awk '{printf "%-10s %-10s\n", $1, $2}' file


Basic Usage

The content of log.txt is as follows:



2 this is a test

3 Do you like awk

This's a test

10 There are orange,apple,mongo

Usage 1: Basic syntax

awk '{ [pattern] action }' filenames

**Note:** The script part of awk must be enclosed in single quotes ' '.

Example 1: Output the 1st and 4th columns of each line



awk '{print $1, $4}' log.txt

Output:

2 a

3 like

This's

10 orange,apple,mongo

Example 2: Formatted output

printf can customize the output format (similar to the printf in the C language):



awk '{printf "%-8s %-10s\n", $1, $4}' log.txt

Output:

2        a

3        like

This's

10       orange,apple,mongo

Usage 2: Specify the separator -F

The -F option is used to specify the separator between columns, equivalent to the built-in variable FS (Field Separator).

Example 1: Use a comma , as the separator



awk -F, '{print $1, $2}' log.txt

Output:



2 this is a test

3 Do you like awk

This's a test

10 There are orange apple

Example 2: Use the built-in variable FS to set the separator



awk 'BEGIN { FS="," } {print $1, $2}' log.txt

The output is the same:



2 this is a test

3 Do you like awk

This's a test

10 There are orange apple

Example 3: Use multiple separators (space or comma)

[ ,] means both space and comma are treated as separators.



awk -F '[ ,]' '{print $1, $2, $5}' log.txt

Output:



2 this test

3 Do awk

This's a

10 There apple

Usage 3: Use -v to set variables

The -v option is used to pass external variables before executing the AWK script, often for dynamic assignment.

Syntax format:



awk -v 变量名=值 '{动作}' 文件名

Example 1: Define a numeric variable and use it in a calculation



awk -va=1 '{print $1, $1+a}' log.txt

Output:

2 3

3 4

This's 1

10 11

Explanation:

When $1 is not a number (such as This's), the result is empty or output as is.

Example 2: Define multiple variables at the same time



awk -va=1 -vb=s '{print $1, $1+a, $1b}' log.txt

Output:



2 3 2s

3 4 3s

This's 1 This'ss

10 11 10s

Explanation:

Usage 4: Use -f to call an external AWK script

When an AWK script is long, you can write the logic into a separate file and load it via the -f parameter.

Syntax format:



awk -f 脚本文件 文件名

Suppose we have a script file cal.awk with the following content:



{ print $1, $1 + 10 }

Execute a command:



awk -f cal.awk log.txt

Output:

2 12

3 13

This's 10

10 20

Explanation:


operator

operator Description
= += -= *= /= %= ^= **= Assignment
?: C Conditional expressions
|| Logical OR
&& Logical AND
~ and !~ Match a regular expression and do not match a regular expression
< <= > >= != == Relational operators
Space Connection
+ - Add, subtract
* / % Multiply, divide, and modulo
+ - ! Unary plus, minus, and logical NOT
^ *** Exponentiation
++ -- Increment or decrement, as a prefix or suffix
$ Field reference
in Array member

Filter rows where the first column is greater than 2



$ awk '$1>2' log.txt    #命令

#输出

3 Do you like awk

This's a test

10 There are orange,apple,mongo

Filter rows where the first column equals 2



$ awk '$1==2 {print $1,$3}' log.txt    #命令

#输出

2 is

Filter rows where the first column is greater than 2 and the second column equals 'Are'



$ awk '$1>2 && $2=="Are" {print $1,$2,$3}' log.txt    #命令

#输出

3 Are you


Built-in variables

Variables Description
$n The nth field of the current record, fields separated by FS
$0 The complete input record
ARGC The number of command-line arguments
ARGIND The position of the current file in the command line (starting from 0)
ARGV An array containing the command-line arguments
CONVFMT Numeric conversion format (default %.6g) ENVIRON environment variable associative array
ERRNO The description of the last system error
FIELDWIDTHS Field width list (separated by spaces)
FILENAME Current file name
FNR Line numbers counted separately for each file
FS Field separator (defaults to any whitespace)
IGNORECASE If true, perform case-insensitive matching
NF The number of fields in a record
NR The number of records read, i.e., the line number, starting from 1
OFMT Numeric output format (default %.6g)
OFS Output field separator; the default is the same as the input field separator.
ORS Output record separator (default is a newline)
RLENGTH The length of the string matched by the match function
RS Record separator (default is a newline)
RSTART The first position of the string matched by the match function
SUBSEP Array subscript separator (default is /034)


$ awk 'BEGIN{printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n","FILENAME","ARGC","FNR","FS","NF","NR","OFS","ORS","RS";printf "---------------------------------------------\n"} {printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n",FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS}'  log.txt

FILENAME ARGC  FNR   FS   NF   NR  OFS  ORS   RS

---------------------------------------------

log.txt    2    1         5    1

log.txt    2    2         5    2

log.txt    2    3         3    3

log.txt    2    4         4    4

$ awk -F\' 'BEGIN{printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n","FILENAME","ARGC","FNR","FS","NF","NR","OFS","ORS","RS";printf "---------------------------------------------\n"} {printf "%4s %4s %4s %4s %4s %4s %4s %4s %4s\n",FILENAME,ARGC,FNR,FS,NF,NR,OFS,ORS,RS}'  log.txt

FILENAME ARGC  FNR   FS   NF   NR  OFS  ORS   RS

---------------------------------------------

log.txt    2    1    '    1    1

log.txt    2    2    '    1    2

log.txt    2    3    '    2    3

log.txt    2    4    '    1    4

# Output sequence number NR, matching text line number

$ awk '{print NR,FNR,$1,$2,$3}' log.txt

---------------------------------------------

1 1 2 this is

2 2 3 Are you

3 3 This's a test

4 4 10 There are

# Specify output delimiter

$  awk '{print $1,$2,$5}' OFS=" $ "  log.txt

---------------------------------------------

2 $ this $ test

3 $ Are $ awk

This's $ a $

10 $ There $


Use a regular expression for string matching



# Output the second column containing "th", and print the second and fourth columns

$ awk '$2 ~ /th/ {print $2,$4}' log.txt

---------------------------------------------

this a

~ indicates the start of a pattern. The // contains the pattern.



# Output lines containing "re"

$ awk '/re/ ' log.txt

---------------------------------------------

3 Do you like awk

10 There are orange,apple,mongo


Case-insensitive



$ awk 'BEGIN{IGNORECASE=1} /this/' log.txt

---------------------------------------------

2 this is a test

This's a test


Negate the pattern



$ awk '$2 !~ /th/ {print $2,$4}' log.txt

---------------------------------------------

Are like

a

There orange,apple,mongo

$ awk '!/th/ {print $2,$4}' log.txt

---------------------------------------------

Are like

a

There orange,apple,mongo


awk scripts

Regarding awk scripts, we need to note two keywords: BEGIN and END.

Suppose there is a file like this (a student grade table):



$ cat score.txt

Marry   2143 78 84 77

Jack    2321 66 78 45

Tom     2122 48 77 71

Mike    2537 87 97 95

Bob     2415 40 57 62

Our awk script is as follows:



$ cat cal.awk

#!/bin/awk -f

#运行前

BEGIN {

    math = 0

    english = 0

    computer = 0

 

    printf "NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL\n"

    printf "---------------------------------------------\n"

}

#运行中

{

    math+=$3

    english+=$4

    computer+=$5

    printf "%-6s %-6s %4d %8d %8d %8d\n", $1, $2, $3,$4,$5, $3+$4+$5

}

#运行后

END {

    printf "---------------------------------------------\n"

    printf "  TOTAL:%10d %8d %8d \n", math, english, computer

    printf "AVERAGE:%10.2f %8.2f %8.2f\n", math/NR, english/NR, computer/NR

}

Let us look at the execution result:



$ awk -f cal.awk score.txt

NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL

---------------------------------------------

Marry  2143     78       84       77      239

Jack   2321     66       78       45      189

Tom    2122     48       77       71      196

Mike   2537     87       97       95      279

Bob    2415     40       57       62      159

---------------------------------------------

  TOTAL:       319      393      350

AVERAGE:     63.80    78.60    70.00


More examples

The hello world program in AWK is:



BEGIN { print "Hello, world!" }

Calculate file size



$ ls -l *.txt | awk '{sum+=$5} END {print sum}'

--------------------------------------------------

666581

Find lines with a length greater than 80 from a file:

awk 'length>80' log.txt

Print the multiplication table



seq 9 | sed 'H;g' | awk -v RS='' '{for(i=1;i<=NF;i++)printf("%dx%d=%d%s", i, NR, i*NR, i==NR?"\n":"\t")}'

More information:

  • How AWK works

  • AWK arrays

  • AWK conditional statements and loops

  • AWK user-defined functions

  • AWK built-in functions

  • 8 powerful Awk built-in variables

  • The official AWK manual

  • Linux Command Reference Linux Command Reference