KSH : mise en forme colonne vers format csv

Résolu/Fermé
dofre114 - Modifié le 12 janv. 2022 à 12:47
dubcek Messages postés 18718 Date d'inscription lundi 15 janvier 2007 Statut Contributeur Dernière intervention 22 mars 2024 - 12 janv. 2022 à 18:00
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
A voir également:

2 réponses

mamiemando Messages postés 33079 Date d'inscription jeudi 12 mai 2005 Statut Modérateur Dernière intervention 23 avril 2024 7 749
12 janv. 2022 à 13:05
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
dubcek Messages postés 18718 Date d'inscription lundi 15 janvier 2007 Statut Contributeur Dernière intervention 22 mars 2024 5 615
12 janv. 2022 à 18:00
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