KSH : mise en forme colonne vers format csv

Résolu
dofre114 -  
dubcek Messages postés 18627 Date d'inscription   Statut Contributeur Dernière intervention   -
Bonjour à tous,

J'ai un petit souci de mise en forme , j'aurai besoin d'un script sur
ksh
. J'ai un fichier de type :

BEGIN
A=toto
B=tata
H=titi
END
BEGIN
A=toto
B=titi
C=tata
D=toto
END
BEGIN
D=toto
E=titi
F=tata
G=tutu
H=tete
END

J'ai besoin de l'avoir au format csv sous ce type :

A;B;C;D;E;F;G;H
toto;tata;;;;;;titi
toto;titi;tata;toto;;;;;
;;;;toto;titi;tata;tutu;tete


Merci d'avance pour votre aide

2 réponses

  1. mamiemando Messages postés 33228 Date d'inscription   Statut Modérateur Dernière intervention   7 944
     
    Bonjour,

    Je te propose cette solution, écrite en python, car en shell c'est un peu "compliqué" à écrire surtout si tu n'as pas d'a priori sur les clés impliquées dans ton fichier.

    #!/usr/bin/env python3
    
    import sys
    
    filename = sys.argv[1]
    entries = list()
    keys = set()
    entry = dict()
    
    with open(filename) as f:
        for line in f.readlines():
            line = line.strip()
            if line == "BEGIN":
                entry = dict()
            elif line == "END":
                entries.append(entry)
            else:
                sp = line.split("=")
                assert len(sp) > 1
                key = sp[0]
                value = "".join(sp[1:])
                entry[key] = value
                keys.add(key)
    
    keys = sorted(keys)
    print(";".join(keys))
    print("\n".join(
        ";".join(
            entry.get(key, "")
            for key in keys
        )
        for entry in entries
    ))


    ... ce qui donne à l'exécution.

    (mando@silk) (~) $ python3 toto.py fichier.txt 
    A;B;C;D;E;F;G;H
    toto;tata;;;;;;titi
    toto;titi;tata;toto;;;;
    ;;;toto;titi;tata;tutu;tete


    Bonne chance
    0
  2. dubcek Messages postés 18627 Date d'inscription   Statut Contributeur Dernière intervention   5 660
     
    hello
    $ cat  f3.awk
    BEGIN { s=split("A B C D E F G H", t); FS="="}
    /BEGIN/ {++n; next}
    /=/ {t2[n][$1]=$2}
    END {for(x=1; x<=s; x++)printf "%s%c", t[x], x==s? "\n": ";"
    for(x=1; x<=n; x++)for(z=1; z<=s; z++)printf "%s%c", t2[x][t[z]], z==s? "\n": ";"}
    $
    $ awk -f f3.awk fichier.txt
    A;B;C;D;E;F;G;H
    toto;tata;;;;;;titi
    toto;titi;tata;toto;;;;
    ;;;toto;titi;tata;tutu;tete
    0