awk 关联数组增量

Ray*_* C. 1 awk

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

我做了一些研究,$4 是第四列,也就是组。a[$4] 将 $4 中的所有项目加载到关联数组中。但是,我不明白 ++== 做什么。

awk -F: 'a[$4]++==2 { print $4 }' passwd     
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Rav*_*h13 6

以下是 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.
Run Code Online (Sandbox Code Playgroud)

这里有 1 件事,即使您的 Input_file 有超过 3 次出现的第 4 个字段,它也只会打印第 3 次出现,因此如果您想打印第 4 个字段出现 2 次或更多次的所有行,则将代码更改为:

awk -F: '++a[$4]>=2 { print $4 }' passwd     
Run Code Online (Sandbox Code Playgroud)

数组执行示例:

假设我们有以下 Input_file:

cat Input_file
a,b,c,1st,bla bla
a,b,c,2nd,bla bla
a,b,c,1st, bla bla
Run Code Online (Sandbox Code Playgroud)

现在创建数组a[$4]++将保存数组中的值,如下所示:

a[1st]=2a[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
Run Code Online (Sandbox Code Playgroud)