awk

一元运算符(Unary Operators)

一个操作它接受一个运算符称为一元运算符。

Operator Description
+ The number (returns the number itself)
- Negate the number
++ Auto Increment
-- Auto Decrement

下面示例使用否定数字使用一元运算符-:

$ awk -F, '{print -$4}' employee-sal.txt
-10000
-5000
-4500
-4500
-3000

下面的列子演示了如何加减一元运算符影响存储在文本文件中的负数:

$ vi negativ.txt
-1
-2
-3
$ awk '{print +$1}' negativ.txt
-1
-2
-3
$ awk '{print -$1}' negativ.txt
1
2
3

自动递增和自动递减运算符更改相关联变量的值; 当在一个正则表达式里使用它们时解释为值可以是 'pre' 或 'post' 改变值.

Pre 的意思是你增加 ++ (或 --) 在变量名之前. 这将这个变量的值首先增加 (或减少) 1, 然后执行在语句的其他部分。 Post意思是你可以增加++ (或 --) 在变量名后面. 这将先执行包含的语句然后再使变量值增加(或减少) 1. pre-auto-increment例子:

$ awk -F, '{print ++$4}' employee-sal.txt
10001
5001
4501
4501
3001

$ awk -F, '{print --$4}' employee-sal.txt
9999
4999
4499
4499
2999

post-auto-increment例子: (自从++在print语句之后,所以原值输出):

$ awk -F, '{print $4++}' employee-sal.txt
10000
5000
4500
4500
3000

(++在一个的隔开的语句之后,结果值被打印输出):

$ awk -F, '{$4++; print $4}' employee-sal.txt
10001
5001
4501
4501
3001

Example of post-auto-decrement: (since -- is in the print statement the original value is printed):

$ awk -F, '{print $4--}' employee-sal.txt
10000
5000
4500
4500
3000

Example of post-auto-decrement: (since -- is in a separate statement the resulting value is printed):

$ awk -F, '{$4--; print $4}' employee-sal.txt
9999
4999
4499
4499
2999

下面是一个有用的例子显示了拥有login shell用户总数,比如谁可以登陆进系统并到达一个命令行提示符。 * 使用post-increment一元运算符(虽然自变量没有打印,但到END块pre-increment产生相同的结果)

* 这个脚本的body块包括一个pattern匹配,因此如果行最后一个字段包含/bin/bash就执行

* 注意:正则表达式应变用//括起来,但是/字符必须被转义在正则表达式里面,以便它不被解释

* 当一行匹配时,变量n被加1,最终的值在END块中被打印。

$ awk -F: '$NF ~/\/bin\/bash/ {n++}; END {print n}' /etc/passwd
3