简体   繁体   English

使用awk按列拆分CSV文件

[英]Using awk to split CSV file by column

I have a CSV file that I need to split by date. 我有一个CSV文件,需要按日期拆分。 I've tried using the AWK code listed below (found elsewhere ). 我尝试使用下面列出的AWK代码(在其他位置找到)。

awk -F"," 'NR>1 {print $0 >> ($1 ".csv"); close($1 ".csv")}' file.csv

I've tried running this within terminal in both OS X and Debian. 我试过在OS X和Debian的终端中运行它。 In both cases there's no error message (so the code seems to run properly), but there's also no output. 在两种情况下都没有错误消息(因此代码似乎可以正常运行),但是也没有输出。 No output files, and no response at the command line. 没有输出文件,并且在命令行没有响应。

My input file has ~6k rows of data that looks like this: 我的输入文件有大约6000行数据,如下所示:

date,source,count,cost
2013-01-01,by,36,0
2013-01-01,by,42,1.37
2013-01-02,by,7,0.12
2013-01-03,by,11,4.62

What I'd like is for a new CSV file to be created containing all of the rows for a particular date. 我想要创建一个新的CSV文件,其中包含特定日期的所有行。 What am I overlooking? 我在俯视什么?

I've resolved this. 我已经解决了 Following the logic of this thread , I checked my line endings with the file command and learned that the file had the old-style Mac line terminators. 按照该线程的逻辑,我使用file命令检查了行尾,并得知该文件具有旧式的Mac行终止符。 I opened my input CSV file with Text Wrangler and saved it again with Unix style line endings. 我使用Text Wrangler打开了输入的CSV文件,并再次使用Unix样式行结尾将其保存。 Once I did that, the awk command listed above worked as expected. 一旦这样做,上面列出的awk命令就会按预期工作。 It took ~5 seconds to create 63 new CSV files broken out by date. 创建日期前后划分的63个新CSV文件花费了大约5秒钟。

For retrieve information in a log file with ";" 用于使用“;”在日志文件中检索信息。 separator I use: 我使用的分隔符:

grep "END SESSION" filename.log | cut -d";" -f2

where 哪里

  -d, --delimiter=DELIM   use DELIM instead of TAB for field delimiter
  -f, --fields=LIST       select only these fields;  also print any line
                          that contains no delimiter character, unless
                          the -s option is specified

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM