行をCSVファイルに変換するコマンド

行をCSVファイルに変換するコマンド

各行の前にスペースがある次の形式のファイルがあります。

 "Western Overseas",
 "Western Overseas",
 "^",
 "--",
 "^",
 "--",
 "--",
 null,
 24995,
 9977,
 "CR",

 "Western Refrigeration Private Limited",
 "Western Refrigeration Private Limited",
 "[ICRA]A",
 "--",
 "[ICRA]A1",
 "--",
 "Stable",
 null,
 14951,
 2346,
 "CR",

次の形式のCSVファイルに変換したいと思います。

 "Western Overseas","Western Overseas","^","--","^","--","--",null,24995,9977,"CR"
 "Western Refrigeration Private Limited","Western Refrigeration Private Limited","[ICRA]A","--","[ICRA]A1","--","Stable",null,14951,2346,"CR"

使用しようとしていますtrが、すべての出力を1行に印刷し、改行を二重改行に置き換えると思うので問題があります。助けてくれてありがとう。

ベストアンサー1

awkの解決策は次のとおりです。

awk '{if(NF){gsub(/^ |,$/,""); printf c $0; c=","}else{printf "\n"; c=""}};END{printf "\n"}'

拡張説明:

{
    if(NF) { # if the line isn't empty
        gsub(/^ |,$/,""); # remove the first space and last comma
        printf c $0; # print the line (without a newline)
        c="," # set c to add a comma for the next field
    } else {
        printf "\n"; # empty line, output a newline
        c="" # don't print a comma for the next entry
    }
};
END {
    printf "\n" # finish off with a newline
}

おすすめ記事