1

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

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]} 

没有输出。

4

3 回答 3

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

此外,请查看此站点以获取更多示例。

于 2013-03-11T07:01:46.987 回答
0

Found an easy solution. Set the output of awk into a variable. Then turn the variable into an array.

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

array=($list)

Typing:

echo ${array[1]}

Will give you the second entry in the array

于 2013-03-11T08:03:02.967 回答
0

你的问题不是很清楚。寻找这样的东西?

awk -F "|" '$2=="Smith" {arr[count++]=$1}
            END {n=length(arr); for (i=0;i<n;i++) print (i+1), arr[i]}' in.file

输出

1 2
2 3
3 4
于 2013-03-11T07:22:45.277 回答