一般形式
awk 'pattern {action }
pattern {action }
… '
awk '/正则/ {print $0}
pattern {action }
… '
例子
•
第一个参数符合正则表达式,默认输出一整行'$1 !~ /J/'
$awk '$1 ~ /J/' inventory-shipped
-| Jan 13 25 15 115
-| Jun 31 42 75 492
-| Jul 24 34 67 436
-| Jan 21 36 64 620
•
Print every line that is longer than 80 characters:
ls -l | awk '$6 == "Nov" { sum += $5 }
END { print sum }'
•
Print every line that is longer than 80 characters:
awk 'length($0) > 80' data
The sole rule has a relational expression as its pattern and has no action—so it uses the default action, printing the record.
•
inventory-shipped: 两个输入源
$ awk '/12/ { print $0 }
> /21/ { print $0 }' mail-list inventory-shipped
-| Anthony 555-3412 anthony.asserturo@hotmail.com A
-| Camilla 555-2912 camilla.infusarum@skynet.be R
-| Fabius 555-1234 fabius.undevicesimus@ucb.edu F
-| Jean-Paul 555-2127 jeanpaul.campanorum@nyu.edu R
-| Jean-Paul 555-2127 jeanpaul.campanorum@nyu.edu R
-| Jan 21 36 64 620
-| Apr 21 70 74 514
Note how the line beginning with ‘Jean-Paul’ in mail-list was printed twice, once for each rule.
•
Print the length of the longest input line:
awk '{ if (length($0) > max) max = length($0) }
END { print max }' data
The code associated with END executes after all input has been read; it’s the other side of the coin to BEGIN.
•
Print the length of the longest line in :
data
expand data | awk '{ if (x < length($0)) x = length($0) }
END { print "maximum line length is " x }'
This example differs slightly from the previous one: the input is processed by the expandutility to change TABs into spaces, so the widths compared are actually the right-margin columns, as opposed to the number of input characters on each line.
•
Print every line that has at least one field:
awk 'NF > 0' data
This is an easy way to delete blank lines from a file (or rather, to create a new file similar to the old file but from which the blank lines have been removed).
•
Print seven random numbers from 0 to 100, inclusive:
awk 'BEGIN { for (i = 1; i <= 7; i++)
print int(101 * rand()) }'
•
Print the total number of bytes used by :
files
ls -l files | awk '{ x += $5 }
END { print "total bytes: " x }'
•
Print the total number of kilobytes used by :
files
ls -l files | awk '{ x += $5 }
END { print "total K-bytes:", x / 1024 }'
•
Print a sorted list of the login names of all users:
awk -F: '{ print $1 }' /etc/passwd | sort
•
Count the lines in a file:
awk 'END { print NR }' data
•
输出行内包含li的整行
$ awk '/li/ { print $0 }' mail-list
When lines containing ‘li’ are found, they are printed because ‘print $0’ means print the current line. (Just ‘print’ by itself means the same thing, so we could have written that instead.)
•
Print the even-numbered lines in the data file:
awk 'NR % 2 == 0' data
If you used the expression ‘NR % 2 == 1’ instead, the program would print the odd-numbered lines.
评论区