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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Capitolo 12. Filtri, programmi e coman<strong>di</strong> esterni<br />

# Verifica la presenza <strong>di</strong> un file <strong>di</strong> input passato da riga <strong>di</strong> comando.<br />

ARG=1<br />

E_ERR_ARG=65<br />

E_NOFILE=66<br />

if [ $# -ne "$ARG" ] # Il numero <strong>di</strong> argomenti passati allo script è corretto?<br />

then<br />

echo "Utilizzo: ‘basename $0‘ nomefile"<br />

exit $E_ERR_ARG<br />

fi<br />

if [ ! -f "$1" ] # Verifica se il file esiste.<br />

then<br />

echo "Il file \"$1\" non esiste."<br />

exit $E_NOFILE<br />

fi<br />

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

# main ()<br />

sed -e ’s/\.//g’ -e ’s/\,//g’ -e ’s/ /\<br />

/g’ "$1" | tr ’A-Z’ ’a-z’ | sort | uniq -c | sort -nr<br />

# =========================<br />

# Frequenza delle occorrenze<br />

# Filtra i punti e le virgole, e cambia gli spazi tra le parole in<br />

#+ linefeed, quin<strong>di</strong> trasforma tutti i caratteri in caratteri minuscoli ed<br />

#+ infine premette il conteggio delle occorrenze e le or<strong>di</strong>na in base al numero.<br />

# Arun Giridhar suggerisce <strong>di</strong> mo<strong>di</strong>ficare il precedente in:<br />

# . . . | sort | uniq -c | sort +1 [-f] | sort +0 -nr<br />

# In questo modo viene aggiunta una chiave <strong>di</strong> or<strong>di</strong>namento secondaria, per cui<br />

#+ nel caso <strong>di</strong> occorrenze uguali queste vengono or<strong>di</strong>nate alfabeticamente.<br />

# Ecco la spiegazione:<br />

# "In effeti si tratta <strong>di</strong> un or<strong>di</strong>namento <strong>di</strong> ra<strong>di</strong>ce, prima sulla<br />

#+ colonna meno significativa<br />

#+ (parola o stringa, opzionalmente senza <strong>di</strong>stinzione minuscolo-maiuscolo)<br />

#+ infine sulla colonna più significativa (frequenza)."<br />

#<br />

# Frank Wang spiega che il precedente equivale a<br />

#+ . . . | sort | uniq -c | sort +0 -nr<br />

#+ così pure il seguente:<br />

#+ . . . | sort | uniq -c | sort -k1nr -k<br />

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

exit 0<br />

# Esercizi:<br />

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

# 1) Aggiungete dei coman<strong>di</strong> a ’sed’ per filtrare altri segni <strong>di</strong><br />

248

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

Saved successfully!

Ooh no, something went wrong!