欠落している列でCSVファイルを構成する

欠落している列でCSVファイルを構成する

質問

列情報がないため、正しく作成されていない.csvファイルがあります。

ファイルは次のとおりです(わかりやすくするためにスペースを使用します)。

  C1,  C2,  C3,  C4,
R1C1,R1C2,R1C3,R1C4,
R2C1,R2C3,    ,    ,
R3C1,R3C4,    ,    ,
...

ここでCxは列ヘッダーで、文字列値を共有しますRyCx。例えば、

Name     , Date       , Address           , Email              ,
Name Alex, Date Sept 3, Address 123 Madeup, Email [email protected],
Name Jenn, Date Sept 4, Email [email protected],                    ,

今、列の正しい位置にありません。Email [email protected]Address

データの後にはスペースがいくらか続くことがあります。データは、R1C1,R1C2,R1C3データがない場合を除き、各行が[...]順に配置されます。この場合、列は左に移動しますが、対応するラベルはCx変更されません。これは、データを出力するプログラムが空セルを生成しないためである。

このデータには他のパターンはありません。

このデータを次のような適切な列に再構成したいと思います。

  C1,  C2,  C3,  C4,
R1C1,R1C2,R1C3,R1C4,
R2C1,    ,R2C3,    ,
R3C1,    ,    ,R3C4,
...

または例では

Name     , Date       , Address           , Email              ,
Name Alex, Date Sept 3, Address 123 Madeup, Email [email protected],
Name Jenn, Date Sept 4,                   , Email [email protected] ,

以前のスーパーコンピュータシミュレーションの結果であった情報を収集した場所に戻ることはできません。


解決策

ありがとう、FKEインターネットとurcodebetterznow。

while IFS= read -r line; do # read input line by line
IFS=, read -ra fields <<<"$line" #separate fields by commas

    j=0; 
        for i in $(cat headers.txt); do #I wrote the headers to a different file

            if [ "${fields[j]}" == "$i" ]; then #replaced with grep -o result because fields are not exact matches for the header, but contain exact matches
                val="${fields[j]}"; : $((j += 1)); 
            else  val=''; 
            fi; 

            printf '%s,' "$val"; #I later used sed to erase the redundant information already in the header
         done

done < datafile.txt > solution.csv

headers.txt ファイルは次のとおりです。

a
b
c
d
e
f
g
h

データは datafile.txt と同じです。

a,b,c,d,e,
a,c,e
b,d,f,g,h
c,d,g,h
d,h
b,f,g
a,d,f,g

私が受け取ったbashスクリプトを実行します(明確にするためにスペースを使用します)。

a,b,c,d,e, , , ,
a, ,c, ,e, , , ,
 ,b, ,d, ,f,g,h,
 , ,c,d, , ,g,h,
 , , ,d, , , ,h,
 ,b, , , ,f,g, ,
a, , ,d, ,f,g, ,

これが私たちが望む結果です。

ベストアンサー1

今書き直された質問は概念的に答えやすいです。データの各行に表示または表示されない可能性があるラベルのセットがあります。各行を読み、列を順番に調べて、その列のタグが予想されるタグであることを確認したいと思います。そうでない場合は、空のセルを挿入し、次の列を確認してください。予想ラベルリストの終わりに達すると、再構成された行がエクスポートされます。

選択した言語で実装できる擬似コードは次のとおりです。

read the first row
split the text on commas to create the array of expected tags
read the next row
    if no more data, exit
    split the text on commas to create a row data array
    for each expected tag
        check the current column in the row's data
        if the tag matches
            write the column data to the output
            advance the current column in the row data
        else
            write a blank column to the output
        terminate the output line

おすすめ記事