Script Bash pour afficher un arbre
Par Ruliane le jeudi 23 avril 2015, 10:22 - Programmation - Lien permanent
Voici un petit script permettant de présenter sous forme d'arbre un fichier CSV sous la forme : enfant;parent
#!/bin/bash currentlevel=0 root='Vertébrés' echo $root # Affiche un arbre à partir du noeud passé en argument function subtree { while IFS=";" read enfant parent do #echo "test $enfant ; $parent" if [ "$parent" == "$1" ] # Cherche et affiche les enfants du noeud actuel then for (( i=0; i<$currentlevel; i++ )) do echo -e -n "| " done echo -e "└------$enfant" currentlevel=$((currentlevel+1)) subtree $enfant currentlevel=$((currentlevel-1)) fi done < animaux.csv }
Exemple de fichier en entrée :
Poissons;Vertébrés Batraciens;Vertébrés Reptiles;Vertébrés Mammifères;Vertébrés Oiseaux;Vertébrés Crapaud;Batraciens Grenouille;Batraciens Reptiles;Lézare Reptiles;Tortue Reptiles;Serpent Carnivores;Mammifères Herbivores;Mammifères Chat;Carnivores Chien;Carnivores
Et le résultat :
ruliane@testsrv01:~$ ./tree.sh Vertébrés └------Poissons └------Batraciens | └------Crapaud | └------Grenouille └------Reptiles └------Mammifères | └------Carnivores | | └------Chat | | └------Chien | └------Herbivores └------Oiseaux ruliane@testsrv01:~$