linux - 如何将数组实现为 AWK 表达式?

标签 linux arrays bash awk multiple-columns

我正在写一个脚本,我有一个看起来像这样的带分隔符的文件。

1|Anderson|399.00|123                                  
2|Smith|29.99|234                                  
3|Smith|98.00|345                                   
4|Smith|29.98|456                                   
5|Edwards|399.00|567  
6|Kreitzer|234.56|456

这是一个 awk 语句,它将获取包含“Smith”的行的第一列中的所有值。

echo $(awk -F '|' 'BEGIN {count=0;} $2=="Smith" {count++; print $1}' customer)

输出将是:

2 3 4

我该怎么做,所以我也将值作为 awk 增量输入到数组中。我试过这个:

echo $(awk -F '|' 'BEGIN {count=0;} $2=="Smith" {count++; arr[count]=$1; print $1}' customer)

编辑:稍后进入脚本,当我输入

echo ${array[1]} 

没有输出。

最佳答案

您的代码似乎是正确的!也许,我可能没有正确回答您的问题?

我稍微增强了您的代码以在执行结束时打印存储在数组中的值。此外,在打印值之前还有一个 print 语句。

echo $(awk -F '|' 'BEGIN {count=0;} $2=="Smith" {count++; arr[count]=$1; print $1} END { print "Printing the inputs"; for (i in arr) print  arr[i] }' customer)
2 3 4 Printing the inputs 2 3 4

进一步看this site更多示例。

关于linux - 如何将数组实现为 AWK 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15332592/

相关文章:

c - 在 Linux 上编写 PID 文件

javascript - 数组推送产生意外的数组

python - 高效的二维数组处理

Bash 脚本,替换文件中的文本?

multithreading - 如何在 bash/replace text/CPU usage 中使函数在后台工作

linux - 如何在 Linux 内核中启用 CONFIG_PREEMPT 选项?

linux - 根据匹配模式将一行行 grep 到 shell 变量中

linux new/delete, malloc/free 大内存块

arrays - 通过将数组 B 附加到数组 A 而不更改数组 A 的值,在 Julia 中定义数组(C)

linux - echo $variable 在 cron 中不起作用