11.04.2013 Views

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

echo "$numero file rinominato."<br />

else<br />

echo "$numero file rinominati."<br />

fi<br />

exit 0<br />

Appen<strong>di</strong>ce A. Script aggiuntivi<br />

# Esercizi:<br />

# --------<br />

# Quali sono i file sui quali lo script non agisce?<br />

# Come può essere risolto il problema?<br />

#<br />

# Riscrivete lo script in modo che elabori tutti i file della <strong>di</strong>rectory<br />

#+ nei cui nomi sono presenti degli spazi, e li rinomini sostituendo<br />

#+ ogni spazio con un trattino <strong>di</strong> sottolineatura (underscore).<br />

Esempio A-3. blank-rename: rinomina file i cui nomi contengono spazi<br />

È una versione ancor più semplice dello script precedente<br />

#! /bin/bash<br />

# blank-rename.sh<br />

#<br />

# Sostituisce gli spazi nei nomi dei file presenti nella <strong>di</strong>rectory<br />

#+ con degli underscore.<br />

UNO=1 # Per gestire correttamente il singolare/plurale<br />

#+ (ve<strong>di</strong> oltre).<br />

numero=0 # Per contare i file effettivamente rinominati.<br />

TROVATO=0 # Valore <strong>di</strong> ritorno in caso <strong>di</strong> successo.<br />

for nomefile in * # Scorre i file della <strong>di</strong>rectory.<br />

do<br />

echo "$nomefile" | grep -q " " # Controlla se il nome del file<br />

if [ $? -eq $TROVATO ] #+ contiene uno/degli spazio(i).<br />

then<br />

fnome=‘basename $nomefile‘ # Elimina il percorso.<br />

n=‘echo $fnome | sed -e "s/ /_/g"‘ # Sostituisce lo spazio<br />

#+ con un underscore.<br />

mv "$fnome" "$n" # Rinomina.<br />

let "numero += 1"<br />

fi<br />

done<br />

if [ "$numero" -eq "$UNO" ] # Per una corretta grammatica.<br />

then<br />

echo "$numero file rinominato."<br />

else<br />

echo "$numero file rinominati."<br />

fi<br />

613

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!