awk输出元素乱序 [英] awk outputting elements out of order

查看:94
本文介绍了awk输出元素乱序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的bash脚本中,我试图使用csv文件中的元素制作两个并行数组.csv文件中可以包含5-40行中的任何内容.

In my bash script I am trying to make two parallel arrays with elements in a csv file. The csv file can have anywhere from 5-40 lines in it.

Array1=($(awk -F, '{a[$1];}END{for (i in a)print i;}' list.csv))
Array2=($(awk -F, '{b[$2];}END{for (i in b)print i;}' list.csv))

但是,执行此操作之后,数组中元素的顺序与文件不匹配,甚至彼此不匹配.就像awk随机获取行一样.为什么会发生这种情况,我该如何解决?谢谢!

After doing this however, the order of the elements in the arrays do not match the file and they do not even match each other. It's like awk is getting lines randomly. Why is this happening, and how can I fix it? Thanks!

推荐答案

Array1=($(awk -F, 'BEGIN{i=0;}{a[i++]=$1;}END{for(x=0;x<i;x++) print a[x];}' list.csv))
Array2=($(awk -F, 'BEGIN{i=0;}{b[i++]=$2;}END{for(x=0;x<i;x++) print b[x];}' list.csv))

在awk中,您具有关联数组,因此,在其中执行for时,不确定是否会按照将它们放入其中的顺序来获取值.如果要订购它们,请使用计数器作为索引,并使用普通的for循环而不是for in.

In awk you have associative arrays, so when you execute the for in it's not sure that you'll get the values in the same order in which you put them inside. If you want to have them ordered use a counter as index and a normal for loop instead of the for in.

这篇关于awk输出元素乱序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆