さまざまな列の対応する値に基づいて列と項目を構成する

さまざまな列の対応する値に基づいて列と項目を構成する

私は大きなものを持っています.csv ファイルの入力カテゴリ(列A)と項目(列B)の2つの列があります。各項目は列Aに特定のカテゴリを持ち、グループ自体より1行上にあります。たとえば、行3〜10は「カラー」カテゴリにあります。 (A2) 該当項目等:

Column A    Column B
Category    Item
colours 
            red
            blue
            pink
            yellow
            brown
            gray
            white
            violet
trees   
            coconut
            weeking wilow
            ginkgo
            dragon tree
            camphor tree
animals 
            sea urchins
            box jelyfish
            insect
            dinosaur
            triceratops
            apatosaurus

.csv ファイルの出力次のようになります。

  • 最初の列が項目になります。
  • 2番目の列はカテゴリになり、特定のカテゴリに対応する各アイテムに対して、そのカテゴリを各行の2番目の列に配置します。デフォルトでは、各項目に対応するカテゴリを複製します。

input.csvコメント

最後に、output.csvファイルは次のようになります。

Column A        Column B
Item            Category
red             colours
blue            colours
pink            colours
yellow          colours
brown           colours
gray            colours
white           colours
violet          colours
    
coconut         trees
weeking wilow   trees
ginkgo          trees
dragon tree     trees
camphor tree    trees
    
sea urchins     animals
box jelyfish    animals
insect          animals
dinosaur        animals
triceratops     animals
apatosaurus     animals

おすすめを使用しようとしています。ここしかし、成功しませんでした:|

Perlスクリプトを使用してこれを行う方法はありますか?それとも、Linuxのターミナルコマンドで実行できる他の方法を提案できますか?

ベストアンサー1

<TAB>別のファイルであるとし、.csv試してみてください。

awk -F"\t" '$1 {CAT = $1} $2 {print $2, CAT}' OFS="\t" file
Item    Category
red     colours
blue    colours
pink    colours
yellow  colours
brown   colours
gray    colours
white   colours
violet  colours
coconut trees
weeking wilow   trees
ginkgo  trees
dragon tree     trees
camphor tree    trees
sea urchins     animals
box jelyfish    animals
insect  animals
dinosaur        animals
triceratops     animals
apatosaurus     animals

最初のフィールド$1が空でない場合は、カテゴリを保存してください。 2番目のフィールドが$2空でない場合は、そのフィールドと保存されたカテゴリを印刷します。

おすすめ記事