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 />

b=‘expr match "$a" ’[0-9]*’‘ # Conteggio numerico.<br />

echo "Il numero <strong>di</strong> cifre all’inizio <strong>di</strong> \"$a\" è $b."<br />

b=‘expr match "$a" ’\([0-9]*\)’‘ # Notate che le parentesi con l’escape<br />

# == == #+ consentono la verifica della sottostringa.<br />

echo "Le cifre all’inizio <strong>di</strong> \"$a\" sono \"$b\"."<br />

echo<br />

exit 0<br />

Importante: L’operatore : può sostituire match. Per esempio, b=‘expr $a : [0-9]*‘ è<br />

l’equivalente esatto <strong>di</strong> b=‘expr match $a [0-9]*‘ del listato precedente.<br />

#!/bin/bash<br />

echo<br />

echo "Operazioni sulle stringhe usando il costrutto \"expr \$stringa : \""<br />

echo "==================================================="<br />

echo<br />

a=1234zipper5FLIPPER43231<br />

echo "La stringa su cui opereremo è \"‘expr "$a" : ’\(.*\)’‘\"."<br />

# Operatore <strong>di</strong> raggruppamento parentesi con escape. == ==<br />

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

#+ Le parentesi con l’escape<br />

#+ verificano una sottostringa<br />

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

# Se non si esegue l’escaping delle parentesi...<br />

#+ allora ’expr’ converte l’operando stringa in un intero.<br />

echo "La lunghezza <strong>di</strong> \"$a\" è ‘expr "$a" : ’.*’‘."# Lunghezza della stringa<br />

echo "Il numero <strong>di</strong> cifre all’inizio <strong>di</strong> \"$a\" è ‘expr "$a" : ’[0-9]*’‘."<br />

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

echo<br />

echo "Le cifre all’inizio <strong>di</strong> \"$a\" sono ‘expr "$a" : ’\([0-9]*\)’‘."<br />

# == ==<br />

echo "I primi 7 caratteri <strong>di</strong> \"$a\" sono ‘expr "$a" : ’\(.......\)’‘."<br />

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

# Ancora, le parentesi con l’escape forzano la verifica della sottostringa.<br />

#<br />

echo "Gli ultimi 7 caratteri <strong>di</strong> \"$a\" sono ‘expr "$a" : ’.*\(.......\)’‘."<br />

# ====== operatore <strong>di</strong> fine stringa ^^<br />

# (in realtà questo vuol <strong>di</strong>re saltare uno o più caratteri finché non viene<br />

#+ raggiunta la sottostringa specificata)<br />

echo<br />

exit 0<br />

241

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

Saved successfully!

Ooh no, something went wrong!