read column from csv file in terminal ignoring the header

旧城冷巷雨未停 提交于 2019-12-12 05:01:49

问题


I'm writting a simple .ksh file to read a single column from a .csv file and then printing the output to the screen:

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

This works fine but I don't want to return the header row, that is the first row of the file. How would I alter the cut command so that it ignore the first value or string. In this case the header is called 'NAME'. I want to print all of the other rows of this file.

That being said, is it easier to loop through from 2:fname as the code is currently written or is it best to alter the cut command?


回答1:


You could do

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

Alternately, the index of the first element of the array is 0: to start the loop at index 1:

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

Demo:

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

Note, you should always put the array expansion in double quotes.



来源:https://stackoverflow.com/questions/34222074/read-column-from-csv-file-in-terminal-ignoring-the-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!