问题描述
我正在学习用 Bash 编写脚本.
I am learning to script in Bash.
我有一个 5 列 22 行的 CSV 文件.我有兴趣从第二列中获取数据并将其放入数组中.
I have a CSV file with 5 columns and 22 rows. I am interested in taking the data from the second column and put it into an array.
我想要的是第一个名称在 array[0]
中,第二个在 array[1]
中,依此类推.
What I want is that the first name be in array[0]
, the second in array[1]
and so on.
Bash 脚本:
#!/bin/sh
IFS=","
eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) )
printf "%s\n" "${eCollection[0]}"
CSV 看起来像这样.没有标题行.
The CSV looks like this. There is no line with headers.
带有 Vl18xx
数字的列是我想要拆分为数组的内容.
The column with the Vl18xx
numbers is what I want to split into an array.
John,Vl1805,VRFname,10.9.48.64/28,10.9.48.78
John,Vl1806,VRFname,10.9.48.80/28,10.9.48.94
John,Vl1807,VRFname,10.9.48.96/28,10.9.48.110
John,Vl1808,VRFname,10.9.48.112/28,10.9.48.126
John,Vl1809,VRFname,167.107.152.32/28,167.107.152.46
bash 脚本没有将第二列放入数组中,我做错了什么?
The bash script is not placing the 2nd column into the array, what am I doing wrong?
推荐答案
移除 IFS=","
赋值,从而让默认的 IFS 值空格、制表符、换行符应用
Remove the IFS=","
assignment thereby letting the default IFS value of space, tab, newline apply
#!/bin/bash
eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) )
printf "%s\n" "${eCollection[0]}"
解释:由于外括号,eCollection
变量是一个数组.它使用来自 $(cut -d ',' -f2 MyAssignment.csv)
子外壳的 IFS 分隔(想想函数或命令行参数)词中的每个元素进行初始化,这是cut
命令与 ','
分隔符一起使用并打印 MyAssignment.csv
文件中的第二个字段 -f2
.
Explained: The eCollection
variable is an array due to the outer parenthesis. It is initialized with each element from the IFS-separated (think function or command line arguments) words which come from the $(cut -d ',' -f2 MyAssignment.csv)
subshell, which is the cut
command used with the ','
delimiter and printing the second field -f2
from the MyAssignment.csv
file.
printf
语句只是显示如何按索引打印任何项目,您也可以尝试 echo "${eCollection[@}]}"
来查看所有元素.
The printf
statement just shows how to print any item by index, you could also try echo "${eCollection[@}]}"
to see all of the elements.
这篇关于BASH - 如何从 CSV 文件的列中提取数据并将其放入数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!