从终端中的 csv 文件中读取列,忽略 header

read column from csv file in terminal ignoring the header

我正在编写一个简单的 .ksh 文件以从 .csv 文件中读取单个列,然后将输出打印到屏幕上:

fname=($(cut -d, -f2 "myfile.csv"))
# loop through these names
for i in ${fname[@]}; 
do echo "$i"
done

这很好用,但我不想 return header 行,即文件的第一行。我将如何更改 cut 命令以使其忽略第一个值或字符串。在这种情况下,header 称为 'NAME'。我想打印此文件的所有其他行。

话虽这么说,从 2:fname 开始循环是否更容易,因为代码是当前编写的,还是最好更改 cut 命令?

你可以做到

fname=($(sed 1d myfile.csv | cut -d, -f2))

或者,数组第一个元素的索引为 0:从索引 1 开始循环:

for i in "${fname[@]:1}"; do

演示:

$ a=(a b c d e f)
$ echo "${a[@]:1}"
b c d e f

注意,您应该始终将数组扩展放在双引号中。