从终端中的csv文件读取列而忽略标题 [英] read column from csv file in terminal ignoring the header

查看:143
本文介绍了从终端中的csv文件读取列而忽略标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这很好用,但是我不想返回标题行,即文件的第一行.我将如何更改cut命令,使其忽略第一个值或字符串.在这种情况下,标题称为"NAME".我要打印此文件的所有其他行.

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.

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

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?

推荐答案

您可以做到

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

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

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

演示:

$ 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.

这篇关于从终端中的csv文件读取列而忽略标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆