Séparer un nom de fichier de son répertoire

Un jour, où j’ai voulu adapter un script shell existant, j’ai eu besoin de séparer le nom d’un fichier du répertoire dans lequel il se trouvait :
/home/tata/toto => /home/tata + toto

D’ailleurs, il existe peut être une commande qui fait ça toute seule comme une grande ^_^

Ce que fait le script :
# ./toto.sh /home/tata/toto
DIR /home/tata/
FILE toto

Ce qu’il y a dedans :

#!/bin/bash

DEBUG= » »
DIR= » »
FILE= » »

new=$1
[ « x$new » = « x » ] && exit 0

while [ « x$FILE » = « x » ]
do
if [ « x$new » != « x » ]
then
taille=`expr length $new`
slash=`expr index $new « / »`
if [ « x$slash » = « x1 » ]
then
[ $DEBUG ] && echo « Supression premier slash »
slash=`expr $slash + 1 `
new=` expr substr $new $slash $taille`
DIR=’/’
fi
slash=`expr index $new « / »`
if [ « x$slash » = « x0″ ]
then
FILE=$new
else
[ $DEBUG ] && echo  » un / dans $new au $slash caractere »
dir=`expr substr $new 1 $slash`
DIR=${DIR}${dir}
slash=`expr $slash + 1`
new=` expr substr $new $slash $taille`
[ $DEBUG ] && echo « dir : $dir »
fi
else
FILE=$DIR
fi
[ $DEBUG ] && sleep 1
done

if [ ${FILE} = ${DIR} ]
then
FILE= » »
fi
echo « DIR $DIR »
echo « FILE $FILE »


Article lu 1602 fois

One comment

  1. Alko dit :

    Ha Ha Ha, quel idiot je fais :

    $ basename /home/tata/toto
    toto

    $ dirname /home/tata/toto
    /home/tata

Laisser un commentaire