【问题标题】:Include header in grep of specific csv columns在特定 csv 列的 grep 中包含标题
【发布时间】:2017-02-05 06:51:23
【问题描述】:

我正在尝试从大型 csv 文件中提取相关信息以进行进一步处理,因此我希望将列名(标题)保存在我的输出 mini-csv 文件中。

我有:

grep "Example" $fixed_file | cut -d ',' -f 4,6 > $outputpath"Example.csv"

在生成包含两列的 csv 文件时效果很好,但我希望标题信息也包含在输出文件中。

【问题讨论】:

    标签: bash csv grep


    【解决方案1】:

    使用命令分组并将head -1 添加到组合中:

    { head -1 "$fixed_file" && grep "Example" "$fixed_file" | cut -d ',' -f 4,6 ;} \
             >"$outputpath"Example.csv
    

    【讨论】:

      【解决方案2】:

      我的建议是用一个 awk 脚本替换您的多命令管道。

      awk '
        BEGIN {
          OFS=FS=","
        }
      
        NR==1;
      
        /Example/ {
          print $4,$6
        }
      ' "$fixed_file" > "$outputpath/Example.csv"
      

      如果您希望您的标题仅包含标题字段字段 4 和 6,您可以将其更改为:

      awk '
        BEGIN {
          OFS=FS=","
        }
      
        NR==1 || /Example/ {
          print $4,$6
        }
      ' "$fixed_file" > "$outputpath/Example.csv"
      

      Awk 脚本由成对的condition { statement } 组成。缺少的语句假定您要打印该行(这就是 NR==1; 打印标题的原因)。

      当然,您可以将其压缩为单行:

      awk -F, 'NR==1||/Example/{print $4 FS $6}' "$fixed_file" > "$outputpath/Example.csv"
      

      【讨论】:

        猜你喜欢
        • 2012-10-06
        • 2018-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多