@@ -1063,6 +1063,38 @@ $ printf '%10s %5i %5i %5i %8.2f \n' $(cat printf.txt)
1063
1063
是由 Alfred Aho,Peter Weinberger 和 Brian Kernighan 创造,awk 这个名字就是这三个创始人名字的首字母。
1064
1064
1065
1065
awk 每次处理一行,处理的最小单位是字段,每个字段的命名方式为:\$ n,n 为字段号,从 1 开始,\$ 0 表示一整行。
1066
+ ``` sh
1067
+ Usage: awk [POSIX or GNU style options] [--] ' program' file ...
1068
+ POSIX options: GNU long options: (standard)
1069
+ -f progfile --file=progfile
1070
+ -F fs --field-separator=fs
1071
+ -v var=val --assign=var=val
1072
+ Short options: GNU long options: (extensions)
1073
+ -b --characters-as-bytes
1074
+ -c --traditional
1075
+ -C --copyright
1076
+ -d[file] --dump-variables[= file]
1077
+ -D[file] --debug[= file]
1078
+ -e ' program-text' --source=' program-text'
1079
+ -E file --exec=file
1080
+ -g --gen-pot
1081
+ -h --help
1082
+ -i includefile --include=includefile
1083
+ -l library --load=library
1084
+ -L[fatal| invalid| no-ext] --lint[= fatal| invalid| no-ext]
1085
+ -M --bignum
1086
+ -N --use-lc-numeric
1087
+ -n --non-decimal-data
1088
+ -o[file] --pretty-print[= file]
1089
+ -O --optimize
1090
+ -p[file] --profile[= file]
1091
+ -P --posix
1092
+ -r --re-interval
1093
+ -s --no-optimize
1094
+ -S --sandbox
1095
+ -t --lint-old
1096
+ -V --version
1097
+ ```
1066
1098
1067
1099
示例:取出最近五个登录用户的用户名和 IP。首先用 last -n 5 取出用最近五个登录用户的所有信息,可以看到用户名和 IP 分别在第 1 列和第 3 列,我们用 \$ 1 和 \$ 3 就能取出这两个字段,然后用 print 进行打印。
1068
1100
@@ -1098,6 +1130,16 @@ root 0
1098
1130
bin 1
1099
1131
daemon 2
1100
1132
```
1133
+ 示例: 过滤日志文件中返回码及其个数
1134
+ ``` sh
1135
+ awk -F" |" ' {print $7}' /opt/logs/interface.log | sort | uniq -c | sort -nrk 1 | awk ' {printf "返回码==%-10s , 返回码个数==%s\n",$2,$1}'
1136
+
1137
+ 示例: 查询某指定文本日志文件中,根据某分隔符的第几个字段的值为指定值的文本在该文本日志件中的打印
1138
+ ` ` ` sh
1139
+ grep " example" logfile.txt | awk -F' ,' ' $2=="example" {print}'
1140
+ ` ` `
1141
+ > ` grep " example" logfile.txt` :首先使用grep命令查找包含" example" 的行,并将结果输出到标准输出。
1142
+ > ` awk -F' ,' ' $2=="example" {print}' ` :然后使用awk命令对grep的输出进行处理。` -F' ,' ` 指定分隔符为逗号。` $2 ==" example" ` 表示只处理第2个字段为" example" 的行。` {print}` 表示打印符合条件的行。
1101
1143
1102
1144
awk 变量:
1103
1145
0 commit comments