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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18669756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:09:37  来源:igfitidea点击:

BASH - How to extract data from a column in CSV file and put it in an array?

arraysbashcsv

提问by DMS

I am learning to script in Bash.

我正在学习在 Bash 中编写脚本。

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.

我有一个包含 5 列和 22 行的 CSV 文件。我有兴趣从第二列中获取数据并将其放入数组中。

What I want is that the first name be in array[0], the second in array[1]and so on.

我想要的是第一个名字在array[0],第二个在array[1]等等。

Bash script:

bash脚本:

#!/bin/sh
IFS=","
eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) )
printf "%s\n" "${eCollection[0]}"

The CSV looks like this. There is no line with headers.

CSV 看起来像这样。没有标题行。

The column with the Vl18xxnumbers is what I want to split into an array.

带有Vl18xx数字的列是我想要拆分为数组的内容。

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

The bash script is not placing the 2nd column into the array, what am I doing wrong?

bash 脚本没有将第二列放入数组中,我做错了什么?

回答by Adam Burry

Remove the IFS=","assignment thereby letting the default IFS value of space, tab, newline apply

删除IFS=","分配从而让空格、制表符、换行符的默认 IFS 值应用

#!/bin/bash

eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) )
printf "%s\n" "${eCollection[0]}"

回答by konsolebox

Better is to use readarray. No need to mind about IFS which could have any value, and is safe from pathname expansion.

更好的是使用readarray. 无需担心 IFS 可能具有任何价值,并且不会受到路径名扩展的影响。

readarray -t eCollection < <(cut -d, -f2 MyAssignment.csv)
printf '%s\n' "${eCollection[0]}"

回答by Aleks-Daniel Jakimenko-A.

Two pure bash solutions:

两种纯 bash 解决方案:

eCollection=()
while IFS=',' read -r _ second _; do
    eCollection+=("$second")
done < file.txt
printf '%s\n' "${eCollection[0]}"



readarray -t eCollection < file.txt
eCollection=("${eCollection[@]#*,}")
eCollection=("${eCollection[@]%%,*}")
printf '%s\n' "${eCollection[0]}"

回答by Md Shihab Uddin

i like to use awk. First split based on ,delimiter and take required column values into array.

我喜欢用awk。首先根据,分隔符拆分并将所需的列值放入数组。

abc=($(tail -n +1 MyAssignment.csv | awk -F ',' '{print ;}'))
echo ${abc[1]}

Index start from 1. If the file contains headers, replace +1with +2to ignore headers.

指数从1开始。如果文件中包含头文件,替代+1+2忽略标题。