问题描述
我是awk的初学者.我创建了一个包含员工信息的文件.有不同部门的员工.我想算一下每个部门有多少员工.喜欢
I am beginner to awk.I have created one file which contains employee information.There are employees in different departments. And i wanna count that how many employees in each department.like
marketing 3
sales 3
production 4
为此,我使用了以下命令.
For that i used following command.
awk 'NR>1 {dept=$5} {count[dept]++} END {for (dept in count) {print dept count[dept]}}' emp
但是在上面的代码中,它计数并显示第一行,即标头.喜欢
But above code it count and displays the first line i.e header also.like
marketing 3
sales 3
department 1
production 4
其中department是列的标题,尽管我使用了NR> 1.以及如何增加空间或增加所有列的宽度..因为它看起来像上面的输出..但我想正确显示它..那么对此有什么解决办法吗?
where department is a header of column which is also counted although i used NR>1..And how to add space or increase the width of all columns.. because it looks like above output.. but i wanna display it properly..So any solution for this?
这是我的输入文件
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 以正确的制表符间隔格式
Use GNU printf for proper tab-spaced formatting
awk 'NR>1 {count[$3]++} END {for (dept in count) {printf "%-15s%-15s\n", dept, count[dept]}}' file
如果printf "%3s"
-
3
:表示输出将填充为3个字符.
3
: meaning output will be padded to 3 characters.
在man awk
中,您可以看到更多详细信息:
From man awk
, you can see more details:
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.
您可以根据需要添加填充计数.对于您指定的输入文件
You can add the padding count as you need. For the input file you specified
$ awk 'NR>1 {count[$3]++} END {for (dept in count) {printf "%-15s%-15s\n", dept, count[dept]}}' file
production 4
marketing 3
sales 3
这篇关于如何跳过文件的第一行-AWK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!