简体   繁体   English

如何将csv文件中的列读入bash中的数组

[英]How to read columns from csv file into array in bash

I have one csv file that is looking like this我有一个看起来像这样的 csv 文件

NameColumn1;NameColumn2;NameColumn3;NameColumn4
Row1;Row1;Row1;Row1;
Row2;Row2;Row2;Row2;
Row3;Row3;Row3;Row3;

I want to take the values in Row1, Row2 and Row3 from NameColumn1 and put them into array,the same for NameColumn2,NameColumn3 and NameColumn4.我想从 NameColumn1 中取出 Row1、Row2 和 Row3 中的值并将它们放入数组中,NameColumn2、NameColumn3 和 NameColumn4 也是如此。

I don't know how much rows I will have but I know the number of columns.我不知道我会有多少行,但我知道列数。 Any help?有什么帮助吗?

Thank you.谢谢你。

Assuming you have four columns假设你有四列

 while read a b c d; do 
   ar1+=($a)
   ar2+=($b)
   ar3+=($c)
   ar4+=($d)
done < <(sed 's/;/\t/g' somefile.txt)

You then have 4x arrays called ar1 through ar4 with the column values in them.然后,您有 4x 数组,称为 ar1 到 ar4,其中包含列值。

With the -a option/flag from the builtin read .使用内置read中的-a选项/标志。

#!/usr/bin/env bash

while IFS=';' read -ra array; do
  ar1+=("${array[0]}")
  ar2+=("${array[1]}")
  ar3+=("${array[2]}")
  ar4+=("${array[3]}")
done < file.csv                                                       

printf '%s\n' "${ar1[@]}" "${ar2[@]}" "${ar3[@]}" "${ar4[@]}"
  • Just need to remember that index of an array starts counting at zero.只需要记住数组的索引从零开始计数。
  • The only advantage of this solution is that you don't need a variable to assign each field.此解决方案的唯一优点是您不需要变量来分配每个字段。

Using @SaintHax answer and a tweak;使用@SaintHax 回答和调整; this worked for my application and similarly formatted data.这适用于我的应用程序和类似格式的数据。 Note the addition of quotes on stored vars, and the removal of the sed command on the redirected file.请注意在存储的变量上添加引号,并在重定向文件上删除 sed 命令。 Removed IFS settings, thanks to @Jetchisel 's comment.感谢@Jetchisel 的评论,删除了 IFS 设置。

while read -r a b c d; do 
    ar1+=("$a")
    ar2+=("$b") 
    ar3+=("$c") 
    ar4+=("$d") 
done < somefile.csv 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM