【发布时间】:2016-03-04 00:59:43
【问题描述】:
我一直在尝试搜索 .csv 文件的特定列以查找包含特定单词的单元格。但是,它仅适用于我的 .csv 文件中的第一行(即标题)。
该文件是一系列超过 10,000 条论坛帖子,第 1 列作为帖子关键字,第 2 列作为帖子文本。下面的标题是'key','annotated sentence'。
key,annotated sentence
"(212, 2)","Got evidence to back that up??
I'm not sure how a stoner's worse than an alcoholic really.
-Wez"
"(537, 5)","Forgive me for laughing; no, not really ha, ha, ha ha ha
Could it be that people here as well as Canada and the rest of the world has figured out your infantile ""grading system of States"" is a complete sham and your very reason for existing is but an anti-constitutional farce and has lost any claims you have or will make? You stand alone now brady, with simply a few still clinging to the false hope of having others pay for your failures and unConstitutional stance so you can sit on your hands while you keep harping on overturning the 2A."
"(595, 0)",So you're actually claiming that it is a lie to say that the UK has a lower gun crime rate than the US? Even if the police were miscounting crimes it's still a huge and unjustified leap in logic to conclude from that that the UK does not have a lower gun crime rate.
"(736, 3)","The anti-abortionists claim a load of **** on many issues. I don't listen to them. To put the ""life"" of an unfertilized egg above that of a person is grotesquely sick IMO. I support any such stem cell research wholeheartedly."
CSV 分隔符是逗号,文本分隔符是“。”
如果我尝试:
awk -F, '$1 ~ /key/ {print}' posts_file.csv > output_file.csv
它会输出标题行没问题。但是,我已经尝试过:
awk -F, '$1 ~ /212/ {print}' posts_file.csv > output_file.csv
awk -F, '$2 ~ /Canada/ {print}' posts_file.csv > output_file.csv
这些都不起作用 - 尽管应该有,但没有找到匹配项。我想不通为什么?有任何想法吗?提前致谢。
【问题讨论】:
-
awk无法正确解析包含嵌入逗号的双引号字段的 CSV 数据,不幸的是;最好的办法是找到一个 CSV 解析器。 -
@mklement0 啊,谢谢!
-
GNU
awk可以用来解析带有嵌入逗号的双引号字段的 CSV 数据(例如,参见 How can I read a CSV file if only non-empty fields are wrapped by double quotes),但这并不容易。然而,即使这样,双引号字段中的换行也存在问题——没有简单的方法来处理这个问题,因为awk读取行并且不知道如何读取多行并且不容易训练以做得更好。因此,虽然我略微不同意 mkelement0 的最初评论,但建议(“使用 CSV 解析器”)是正确的。 -
@JonathanLeffler:所以我想正确的说法是:一种风格的 Awk 可以做到(GNU Awk,使用 field-匹配变量
FPAT,如您的链接答案所示),并且仅(合理地)如果(双引号)字段没有嵌入的换行符。否则使用 CSV 解析器。 -
@mklement0:是的,这是一个公平的总结。我不知道我是否会费心尝试创建一个正则表达式,它会发现一行的最后一个字段不完整,因此在完成之前读取更多行,然后担心用 FPAT 等拆分它。在在这一点上,你几乎肯定会更好地使用 CSV 解析器,而不仅仅是
awk。