开发者

Looping array issue

开发者 https://www.devze.com 2023-03-20 03:39 出处:网络
I\'m having hard time trying to figure out how to loop through a simple array. I have this text file and basically my goal is selecting all lines starting with digits and an a (which in english is the

I'm having hard time trying to figure out how to loop through a simple array. I have this text file and basically my goal is selecting all lines starting with digits and an a (which in english is the equivalent to 1st, 2nd, 3th, 4th and so forth) and assign them with the proper score. So I have written this code:

#!/usr/bin/awk -f
BEGIN{FS="\t"}
/[0-9]+a/ {for (i=1; i<NR; i++) { score[i]=$3 } for (i=1; i<NR; i++) {print i, score[i]}}

and this is the crazy output I'm getting:

1 25
1 20
2 20
1 16
2 16
3 16
1 13
2 13
3 13
4 13
1 11
2 11
3 11
4 11
5 11
1 10
2 10
3 10
4 10
5 10
6 10
1 9
2 9
3 9
4 9
5 9
6 9
7 9
1 8
2 8
3 8
4 8
5 8
6 8
7 8
8 8
1 7
2 7
3 7
4 7
5 7
6 7
7 7
8 7
9 7
1 6
2 6
开发者_如何学Go3 6
4 6
5 6
6 6
7 6
8 6
9 6
10 6
1 5
2 5
3 5
4 5
5 5
6 5
7 5
8 5
9 5
10 5
11 5
1 4
2 4
3 4
4 4
5 4
6 4
7 4
8 4
9 4
10 4
11 4
12 4
1 3
2 3
3 3
4 3
5 3
6 3
7 3
8 3
9 3
10 3
11 3
12 3
13 3
1 2
2 2
3 2
4 2
5 2
6 2
7 2
8 2
9 2
10 2
11 2
12 2
13 2
14 2
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 1
12 1
13 1
14 1
15 1

and I don't understand how it is possible. Can you please give me help?


While awk arrays are rather hashes, there is no problem in feeding them with data; you just need:

/[0-9]+a/{scores[$1]=$2}

and scores['1a']=25, scores['3a']=16, etc.

You can loop though it using for-in loop:

/END/{for(e in scores) print(e,scores[e])}


You don't need an array for that:

awk '/^[0-9]a/' YOURINPUT 
1a      25
2a      20
3a      16
4a      13
5a      11
6a      10
7a      9
8a      8
9a      7
0

精彩评论

暂无评论...
验证码 换一张
取 消