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

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

问题描述

操作系统:OSX
方法:从命令行,所以使用sed,cut,gawk,虽然最好不要安装模块。

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

所以我想要第一列。

这是我到目前为止所尝试的:

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风格或甚至old-Mac风格的行结尾,这可能会导致奇怪的行为。尝试运行文件in.csv 并查看它出现了什么。

Maybe line endings are biting you here? If the file has DOS-style or even old-Mac-style line endings, this might cause strange behaviour. Try running file in.csv and see what it comes up with.

$ 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上,它似乎 flip 是你想要的

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

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

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