Awk 关联数组增量

Awk 关联数组增量,awk,Awk,我有一个awk命令,我试图理解它的功能。我已从etc/passwd复制了该文件 我做了一些研究,认为4美元是第四栏,这是团体。a[$4]将$4中的所有项目加载到关联数组中。但是,我不明白+++==做什么 awk -F: 'a[$4]++==2 { print $4 }' passwd 非常感谢 以下是OP对所显示代码的解释,仅用于解释目的,不用于运行所显示的代码 -F: ##Setting field separator as colon

我有一个awk命令,我试图理解它的功能。我已从etc/passwd复制了该文件

我做了一些研究,认为4美元是第四栏,这是团体。a[$4]将$4中的所有项目加载到关联数组中。但是,我不明白+++==做什么

awk -F: 'a[$4]++==2 { print $4 }' passwd     

非常感谢

以下是OP对所显示代码的解释,仅用于解释目的,不用于运行所显示的代码

-F:                       ##Setting field separator as colon here.
a[$4]++                   ##Creating array a with index/key 4th field of current line and ++ will do increment to its same occurrence here, to get to know how many times same 4th field has occurred.
==2                       ##Then checking condition if it has count 2 here(occurrence of same 4th field in array a has its count 3(since we are doing post increment)) then do following.
{ print $4 }' passwd      ##Printing 4th field of that line.
这里的一件事是,即使您的输入_文件有3次以上的第4个字段,它也只会打印第3次,因此如果您想打印第4个字段出现2次或更多次的所有行,请将代码更改为:

awk -F: '++a[$4]>=2 { print $4 }' passwd     
阵列执行的示例:

假设我们有以下输入文件:

cat Input_file
a,b,c,1st,bla bla
a,b,c,2nd,bla bla
a,b,c,1st, bla bla
现在使用[$4]++创建数组将在数组中保存如下值:

a[1st]=2,a[2nd]=1等等,为了让OP理解,我以这种方式展示它

我们可以通过遍历数组内部的for循环来了解这一点,如:

awk 'BEGIN{FS=","} {a[$4]++} END{for(key in a){print "Index of array is:" key " And value is:" a[key]}}'  Input_file
Index of array is:2nd And value is:1
Index of array is:1st And value is:2

以下是OP对所显示代码的解释,仅用于解释目的,不用于运行所显示的代码

-F:                       ##Setting field separator as colon here.
a[$4]++                   ##Creating array a with index/key 4th field of current line and ++ will do increment to its same occurrence here, to get to know how many times same 4th field has occurred.
==2                       ##Then checking condition if it has count 2 here(occurrence of same 4th field in array a has its count 3(since we are doing post increment)) then do following.
{ print $4 }' passwd      ##Printing 4th field of that line.
这里的一件事是,即使您的输入_文件有3次以上的第4个字段,它也只会打印第3次,因此如果您想打印第4个字段出现2次或更多次的所有行,请将代码更改为:

awk -F: '++a[$4]>=2 { print $4 }' passwd     
阵列执行的示例:

假设我们有以下输入文件:

cat Input_file
a,b,c,1st,bla bla
a,b,c,2nd,bla bla
a,b,c,1st, bla bla
现在使用[$4]++创建数组将在数组中保存如下值:

a[1st]=2,a[2nd]=1等等,为了让OP理解,我以这种方式展示它

我们可以通过遍历数组内部的for循环来了解这一点,如:

awk 'BEGIN{FS=","} {a[$4]++} END{for(key in a){print "Index of array is:" key " And value is:" a[key]}}'  Input_file
Index of array is:2nd And value is:1
Index of array is:1st And value is:2

++和==是两个独立的运算符。++是[$4]++的后增量,==是比较。用空格将其写得更清楚:a[$4]+==2。顺便说一句,后修复意味着比较[$4]的前一个值,即返回旧值,但随后增加。a[$4]++将[$4]增加1,==2检查它是否为2。该脚本基本上会将第4列中出现的每个值打印两次以上。++和==是两个独立的运算符。++是[$4]++的后增量,==是比较。用空格将其写得更清楚:a[$4]+==2。顺便说一句,后修复意味着比较[$4]的前一个值,即返回旧值,但随后增加。a[$4]++将[$4]增加1,==2检查它是否为2。该脚本基本上会将第4列中出现的每个值打印两次以上。