【问题标题】:Parse a CSV file extracting some of the values but not all解析提取一些值但不是全部的 CSV 文件
【发布时间】:2010-05-19 04:13:16
【问题描述】:

早安,

我有一个本地 csv 文件,其中的值每天都在变化,名为 DailyValues.csv
我需要提取category2和category4的value字段。
然后从提取的值中组合、排序和删除重复项(如果有)。
然后将其保存到新的本地文件 NewValues.txt。

以下是 DailyValues.csv 文件的示例:

category,date,value  
category1,2010-05-18,value01  
category1,2010-05-18,value02  
category1,2010-05-18,value03  
category1,2010-05-18,value04  
category1,2010-05-18,value05  
category1,2010-05-18,value06  
category1,2010-05-18,value07  
category2,2010-05-18,value08  
category2,2010-05-18,value09  
category2,2010-05-18,value10  
category2,2010-05-18,value11  
category2,2010-05-18,value12  
category2,2010-05-18,value13  
category2,2010-05-18,value14  
category2,2010-05-18,value30  
category3,2010-05-18,value16  
category3,2010-05-18,value17  
category3,2010-05-18,value18  
category3,2010-05-18,value19  
category3,2010-05-18,value20  
category3,2010-05-18,value21  
category3,2010-05-18,value22  
category3,2010-05-18,value23  
category3,2010-05-18,value24  
category4,2010-05-18,value25  
category4,2010-05-18,value26  
category4,2010-05-18,value10  
category4,2010-05-18,value28  
category4,2010-05-18,value11  
category4,2010-05-18,value30  
category2,2010-05-18,value31  
category2,2010-05-18,value32  
category2,2010-05-18,value33  
category2,2010-05-18,value34  
category2,2010-05-18,value35  
category2,2010-05-18,value07

我在http://www.php.net/manual/en/function.fgetcsv.php 找到了一些有用的解析示例,并设法提取了 value 列的所有值,但不知道如何将其限制为仅提取 category2/4 的值,然后排序并清除重复项。

解决方案需要在 php、perl 或 shell 脚本中。

任何帮助将不胜感激。
提前谢谢你。

【问题讨论】:

    标签: php csv parsing fgetcsv


    【解决方案1】:

    这是一个 shell 脚本解决方案。

    egrep 'category4|category2' input.file | cut -d"," -f1,3 | sort -u > output.file
    

    我使用cut 命令只是为了向您展示您只能提取某些列,因为用于剪切的f 开关会选择您要提取的列。

    用于排序的u 开关使输出是唯一的。

    编辑: 使用egrep 而不是grep 很重要,因为grep 使用了一些受限制的正则表达式集,而 egrep 有更多的功能

    编辑(对于只有 grep 可用的人):

    grep 'category2' input.file > temp.file && grep 'category4' input.file >> temp.file && cut temp.file -d"," -f1,3 | sort -u > output.file && rm temp.file
    

    它产生了相当大的开销,但仍然有效......

    【讨论】:

    • 谢谢您,非常感谢您。 cut 部分单独工作很好(对我来说是新的),但是当我使用带有 egrep 的完整命令来执行限制时,它会产生一个空文件。
    • 现在这很奇怪。看,为了检查我是否将它从终端正确复制到 SO,我将它复制并粘贴到终端并且它工作......你确定你安装了egrep 吗?检查which egrep
    • 已安装 ` > which egrep /bin/egrep > ls -l /bin/egrep lrwxrwxrwx 1 root root 4 Mar 1 2008 /bin/egrep -> grep ` 我尝试了 grep 和 egrep 和同样的事情没有输出。
    • 哈哈你看,egrep 链接到grep,所以你实际上没有egrep,我发布的正则表达式在grep 中不起作用。试试我刚刚发布的非 egrep 版本。
    • egrep 是链接到 grep 还是上面的其他方式?我实际上有两个实际文件 /bin/egrep /bin/grep。我尝试了您的新示例,它有效,谢谢一百万。但是后来我回去用 egrep 做了第一个,但是像 /bin/egrep 这样使用 egrep 的完整路径,这次它工作得很好。所以这是环境的问题。路径。
    猜你喜欢
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多