读取的CSV文件与引号无关

时间:2018-07-10 14:13:41

标签: bash csv

我有一个包含很多信息的csv文件,我需要创建一个脚本来创建wordpress中包含该文件中信息的帖子。对于大多数信息来说,这还可以,但是我被包含,的文本值的列所阻塞。

以下是失败的列的一个示例:

other_information,"my text, my other text",other_information

脚本:

  list_posts="$(wp post list --post_type=post --field=ID)"
  loop=0;
  while IFS=, read col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11 col12 col13 col14 col15 col16 col17 col18 col19 col20 col21 col22
  do
    if [ "$loop" != "0" ]
    then
      update=0;
      if [ "$list_posts" != "" ]
      then
        for post in $list_posts
        do
          reference_agence="$(wp post meta get $post wpcf-reference-agence)";
          if [ "$reference_agence" = "$col2" ]
          then
            update=1;
            wp post meta update $post wpcf-reference-agence $col2;
            wp post meta update $post wpcf-type-d-annonce $col3;
            wp post meta update $post wpcf-type-bien $col4;
            wp post meta update $post wpcf-code-post $col5;
            wp post meta update $post wpcf-ville $col6;
            wp post meta update $post wpcf-property-location "$col21";
            echo "Update $post réalisé";
          fi
        done
      fi
      if [ "$update" = "0" ]
      then
        post="$(wp post create --post_title="$col1" --post_content="$col2" --post_author=1 --post_type=post --post_status=publish --porcelain)";
        wp post meta update $post wpcf-reference-agence $col2;
        wp post meta update $post wpcf-type-d-annonce $col3;
        wp post meta update $post wpcf-type-bien $col4;
        wp post meta update $post wpcf-code-post $col5;
        wp post meta update $post wpcf-ville $col6;
        wp post meta update $post wpcf-property-location "$col8";
       echo "Création $post réalisé";
      fi
    else
      loop=1;
    fi
  done < annonces.csv

Col21是我只有"my text的数据库和col22 my other text"中的问题。那么我的脚本出了什么问题?

1 个答案:

答案 0 :(得分:0)

如果使用awk,则可以使用awk变量FPAT来指定如何从一行中解析字段。这将使您可以按$1$2$3,...

访问列
line='other_information,"my text, my other text",other_information'
echo $line | awk -vFPAT='[^,]*|"[^"]*"' '{ printf("%s\n%s\n%s\n", $1, $2, $3); }'

会打印

other_information
"my text, my other text"
other_information

然后,您可以使用它来读取所有字段(通过在各自的行上打印每个字段并进行几次read调用,或者编写一个小的awk脚本而不是bash来执行此操作)。

相关问题