我是 awk 的初学者。 我创建了一个包含员工信息的文件。 不同部门都有员工。我想算一下每个部门有多少员工。 喜欢
marketing 3
sales 3
production 4
为此,我使用了以下命令。
awk 'NR>1 {dept=$5} {count[dept]++} END {for (dept in count) {print dept count[dept]}}' emp
但是上面的代码它会计数并显示第一行,即标题。 喜欢
marketing 3
sales 3
department 1
production 4
其中部门是列标题,尽管我使用 NR>1,但它也被计算在内。 以及如何添加空间或增加所有列的宽度..因为它看起来像上面的输出..但我想正确显示它.. 那么有什么解决办法吗?
这是我的输入文件
empid empname department
101 ayush sales
102 nidhi marketing
103 priyanka production
104 shyam sales
105 ami marketing
106 priti marketing
107 atuul sales
108 richa production
109 laxman production
110 ram production
使用 GNU printf 进行正确的制表符间隔格式
awk 'NR>1 {count[$3]++} END {for (dept in count) {printf "%-15s%-15s\n", dept, count[dept]}}' file
您可以将
printf
与 width
选项一起使用,如下例所示,如果 printf "%3s"
3
:表示输出将被填充到 3 个字符。 从
man awk
,你可以看到更多细节:
width The field should be padded to this width. The field is normally padded
with spaces. If the 0 flag has been used, it is padded with zeroes.
.prec A number that specifies the precision to use when printing. For the %e,
%E, %f and %F, formats, this specifies the number of digits you want
printed to the right of the decimal point. For the %g, and %G formats,
it specifies the maximum number of significant digits. For the %d, %o,
%i, %u, %x, and %X formats, it specifies the minimum number of digits to
print. For %s, it specifies the maximum number of characters from the
string that should be printed.
您可以根据需要添加填充数。对于您指定的输入文件
$ awk 'NR>1 {count[$3]++} END {for (dept in count) {printf "%-15s%-15s\n", dept, count[dept]}}' file
production 4
marketing 3
sales 3
您可以使用 tail 跳过特定数量的标题行。这是一个例子:
command | awk '{print $1}' | tail -n +2
对命令结果的第一列执行 awk 后,这将跳过第一行。
我鼓励您使问题的标题更加具体。标题中问题的答案是使用
NR>1
,正如您所发现的。
$ awk 'NR>1 { print $0 }' emp
101 ayush sales
102 nidhi marketing
103 priyanka production
104 shyam sales
105 ami marketing
106 priti marketing
107 atuul sales
108 richa production
109 laxman production
110 ram production
接下来,我无法使用您提供的输入和命令重现您的输出。提供可重现的示例很有帮助。
$ awk 'NR>1 {dept=$5} {count[dept]++} END {for (dept in count) {print dept count[dept]}}' emp
11
我们需要对此命令执行 3 件事才能获得所需的输出。
$ awk 'NR>1 { dept=$3 } { count[dept]++ } END { for (dept in count) { print dept count[dept] } }' emp
1
production4
sales3
marketing3
NR>1
,但它仅应用于第一个操作。每个动作都用大括号 ({ }
) 指定。这可以通过组合两个操作并用分号 (;
) 分隔来解决。
$ awk 'NR>1 { dept=$3; count[dept]++ } END { for (dept in count) { print dept count[dept] } }' emp
production4
sales3
marketing3
awk 'NR>1 { dept=$3; count[dept]++ } END { for (dept in count) { printf "%-16s\t%4d\n", dept, count[dept] } }' emp
production 4
sales 3
marketing 3