将 csv 文件的第一列解析为新文件 [英] Parsing the first column of a csv file to a new file
问题描述
操作系统: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 # Then pasted the example input followed by Ctrl+D:
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 风格的行尾,这可能会导致奇怪的行为.尝试运行 file 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 上,似乎 翻转
就是你想要的.
On OS X, it seems flip
is what you want.
这篇关于将 csv 文件的第一列解析为新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!