解析csv文件的第一列到一个新文件 [英] Parsing the first column of a csv file to a new file

查看:124
本文介绍了解析csv文件的第一列到一个新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

操作系统:OSX
方法:在命令行中,因此使用SED,切,呆子,虽然preferably没有安装模块。

Operating System: OSX Method: From the command line, so using sed, cut, gawk, although preferably no installing modules.

从本质上讲,我试图采取一个CSV文件的第一列,并将其解析到一个新文件。

Essentially I am trying to take the first column of a csv file and parse it to a new file.

例输入文件

EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6

欲望输出

EXAMPLEfoo 
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4

所以我想的第一列。

So I want the first column.

下面是我到目前为止已经试过:

Here is what I have tried so far:

awk -F"," '{print $1}' in.csv > out.txt

awk -F"," '{for (i=2;i<=NF;i++)}' in.csv > out.txt

awk -F"," 'BEGIN { OFS="," }' '{print $1}' in.csv > out.txt

cat in.csv | cut -d \, -f 1 > out.txt

似乎都不上班,要么他们只是打印的第一行或什么都没有,所以我会假设它的失败读取一行行。

None seem to work, either they just print the first line or nothing at all, so I would assume it's failing to read line by line.

推荐答案

您最后的选择完美的作品对我来说:

Your last option works perfectly for me:

$ cat > in.csv
EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6
[Ctrl+D]
$ cat in.csv | cut -d, -f1
EXAMPLEfoo
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4

也许行结尾都在这里咬你?如果文件具有DOS样式,甚至旧的Mac风格的行结束符,这可能会导致奇怪的行为。尝试运行文件in.csv ,看看它来了。

$ file in.unix.csv
in.unix.csv: ASCII text
$ file in.dos.csv
in.dos.csv: ASCII text, with CRLF line terminators

如果后者是您的情况,使用 DOS2UNIX的工具转换文件。

If the latter is your situation, use the dos2unix tool to convert the file.

编辑:在OS X上,似乎 翻转是你想要什么

On OS X, it seems flip is what you want.

这篇关于解析csv文件的第一列到一个新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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