首页·终端命令

awk

文本处理

用法

awk '{print $1}' [file]

把每行切成字段再跑一段小程序;$0 是整行、$1 是第一个字段,默认分隔符是连续的空白而不是单个空格。

常用选项

选项含义
-FSet the field separator, as in -F,
-vPass a shell value in as an awk variable
-fRead the program from a file
$0The whole line; $1 is the first field, NF the field count

示例

awk -F, '{print $2}' data.csv

Second column of a comma-separated file.

awk '$3 > 100' access.log

Only the rows whose third field exceeds 100.

awk '{s+=$1} END {print s}' nums.txt

Adds up the first column.

它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. awk 是做什么的?

把每行切成字段再跑一段小程序;$0 是整行、$1 是第一个字段,默认分隔符是连续的空白而不是单个空格。

Q. 怎么写?

awk '{print $1}' [file] —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 4 个,完整列表在 man awk。这条命令属于文本处理。

相关命令

man 手册: man awk