且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

BASH - 如何从 CSV 文件的列中提取数据并将其放入数组中?

更新时间:2022-03-26 22:18:11

移除 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.