Linux Tutorial – Puntata 25

di jolek78

Care/i fruitrici e fruitori del blog, in questi post – ogni domenica mattina – si parlerà del sistema operativo GNU/Linux e degli strumenti per utilizzarlo al massimo delle potenzialità. Cercheremo di spiegare come funziona, cosa è il kernel, come costruirsi una vpn, come settare un firewall e giocare col terminale, usare adb e altro. Se il capitalismo della sorveglianza ci vuole passivi consumatori-consumatrici di servizi noi si risponde con un po’ di “cultura informatica” e un MARAMEO (quasi affettuoso). Buona lettura!

Domenica, tempo di relax, tempo di Linux Tutorial. Siamo arrivati ormai alla puntata 25, e continuiamo nei tool basilari che ci permettono di manipolare lo stdin in un nuovo, e spesso più leggibile, stdout. Durante quest’ultima settimana molte cose sono successe, una su tutte: preso da un raptus di “ripartiamo da zero che è meglio” ho deciso di formattare la mia macchina Linux, e quindi, conseguentemente ho perso la macchina virtuale della bottega. Ma, ma, ma. Dopo due notti, ci siamo di nuovo: la macchina virtuale è bella e splendente come prima, forse anche un po’ più sicura (ma non entrerò nei dettagli per ora, poi vedrete). Inoltre è successo anche qualcos’altro: ho comprato un Nexus5 rigenerato per davvero pochi pound, ed ho deciso d’installargli sopra una versione mobile di Linux: Ubuntu-Touch. Che forse, dico forse, vedrete su queste pagine. Dunque, tempo al tempo, e cominciamo. Lunga vita a sed!

SED
Dunque, anche questa volta utilizzeremo il file “the rhyme of the ancient mariner” che abbiamo utilizzato anche nelle puntate precedenti. Sed – Stream EDitor – e’ un tool espressamente creato per cercare, modificare e inserire pezzi di “roba” (pensieri parole, opere ed… opinioni?) all’interno di altra “roba”.

bottega@bottegadelbarbieri  ~/Documents  man sed |head -n 15
SED(1)                      User Commands                                            SED(1)

NAME
       sed - stream editor for filtering and transforming text

SYNOPSIS
       sed [OPTION]... {script-only-if-no-other-script} [input-file]...

DESCRIPTION
       Sed  is  a stream editor.  A stream editor is used to perform basic text transformations on an input stream
       (a file or input from a pipeline).  While in some ways similar to an editor which  permits  scripted  edits
       (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient.  But
       it is sed's ability to filter text in a pipeline which particularly distinguishes it from  other  types  of
       editors.

Nella sostanza permette, per esempio, di modificare un file di testo “on the fly”, senza dover aprire un editor, e anche in maniera piuttosto rapida. Per fare questo anche sed utilizza le sempre citate “espressioni regolari” di cui si e’ parlato nella puntata 22.Dunque, prima di tutto ricordiamoci come era fatto il nostro file;

bottega@bottegadelbarbieri  ~  head -n 20 the-rhyme-of-the-ancient-mariner.txt 
PART THE FIRST.
     It is an ancient Mariner,
     And he stoppeth one of three.
     "By thy long grey beard and glittering eye,
     Now wherefore stopp'st thou me?

     "The Bridegroom's doors are opened wide,
     And I am next of kin;
     The guests are met, the feast is set:
     May'st hear the merry din."

     He holds him with his skinny hand,
     "There was a ship," quoth he.
     "Hold off! unhand me, grey-beard loon!"
     Eftsoons his hand dropt he.

     He holds him with his glittering eye--
     The Wedding-Guest stood still,
     And listens like a three years child:

s/ – replacing strings –
Immaginate per ipotesi di avere un file (il nostro) con tante parole uguali che vogliamo modificare. Facciamo finta quindi di voler vedere a schermo la modifica di tutte le parole “Mariner” con la parola “pippo”. Scriveremo:

bottega@bottegadelbarbieri  ~  sed 's/Mariner/pippo/' the-rhyme-of-the-ancient-mariner.txt |head -n 20 
PART THE FIRST.
     It is an ancient pippo,
     And he stoppeth one of three.
     "By thy long grey beard and glittering eye,
     Now wherefore stopp'st thou me?

     "The Bridegroom's doors are opened wide,
     And I am next of kin;
     The guests are met, the feast is set:
     May'st hear the merry din."

     He holds him with his skinny hand,
     "There was a ship," quoth he.
     "Hold off! unhand me, grey-beard loon!"
     Eftsoons his hand dropt he.

     He holds him with his glittering eye--
     The Wedding-Guest stood still,
     And listens like a three years child:

s/ || /g – modifying strings –
Ora, la modifica vi piace, ma come fate a riportarla direttamente nel file, senza vederla a schermo immediatamente? Facciamo una cosa prima: poiché non vogliamo rovinare la novella di Coleridge perché sicuramente se ne avrebbe a male, creiamo una copia di quel file e lavoriamo su quello:

bottega@bottegadelbarbieri  ~  touch the-rhyme-of-the-ancient-mariner_copy.txt
'the-rhyme-of-the-ancient-mariner.txt' -> 'the-rhyme-of-the-ancient-mariner_copy.txt'

E poi scriveremo:

bottega@bottegadelbarbieri  ~  sed 's/Mariner/pippo/g' the-rhyme-of-the-ancient-mariner.txt >> the-rhyme-of-the-ancient-mariner_copy.txt

bottega@bottegadelbarbieri  ~  head the-rhyme-of-the-ancient-mariner_copy.txt
PART THE FIRST.

It is an ancient pippo,
And he stoppeth one of three.
"By thy long grey beard and glittering eye,
Now wherefore stopp'st thou me?

"The Bridegroom's doors are opened wide,
And I am next of kin;
The guests are met, the feast is set:

Come vedete abbiamo introdotto il simbolo >> che permette di scrivere su un file aggiungendo linee in coda.

Per ricapitolare:
/s ci permette di modificare e visualizzare le modifiche
/s + /g ci permette di modificare ma non visualizzare le modifiche

Queste sono essenzialmente le due funzioni più utilizzate in assoluto di sed. Ma ovviamente ve ne sono molte altre. Andiamo a esplorarne alcune.

s/^ – insert at beginning –
Immaginate ora di voler inserire il simbolo del cancelletto all’inizio di ogni linea del vostro file. Ovviamente, in questo caso, utilizzeremo l’espressione regolare ^:

bottega@bottegadelbarbieri  ~  sed 's/^/#/' the-rhyme-of-the-ancient-mariner.txt |head -n 20 
#PART THE FIRST.
#     It is an ancient Mariner,
#     And he stoppeth one of three.
#     "By thy long grey beard and glittering eye,
#     Now wherefore stopp'st thou me?
#
#     "The Bridegroom's doors are opened wide,
#     And I am next of kin;
#     The guests are met, the feast is set:
#     May'st hear the merry din."
#
#     He holds him with his skinny hand,
#     "There was a ship," quoth he.
#     "Hold off! unhand me, grey-beard loon!"
#     Eftsoons his hand dropt he.
#
#     He holds him with his glittering eye--
#     The Wedding-Guest stood still,
#     And listens like a three years child:

s/$ – insert at the end –
Immaginate ora invece di voler inserire il carattere cancelletto # alla fine di ogni linea. In questo caso, utilizzeremo l’espressione regolare $:

bottega@bottegadelbarbieri  ~  sed 's/$/ #/' the-rhyme-of-the-ancient-mariner.txt |head -n 20 
PART THE FIRST. #
     It is an ancient Mariner, #
     And he stoppeth one of three. #
     "By thy long grey beard and glittering eye, #
     Now wherefore stopp'st thou me? #

     "The Bridegroom's doors are opened wide, #
     And I am next of kin; #
     The guests are met, the feast is set: #
     May'st hear the merry din." #

     He holds him with his skinny hand, #
     "There was a ship," quoth he. #
     "Hold off! unhand me, grey-beard loon!" #
     Eftsoons his hand dropt he. #

     He holds him with his glittering eye-- #
     The Wedding-Guest stood still, #
     And listens like a three years child: #

-n ‘np’ – print numbered lines –
Possiamo usare sed come si utilizza cat – concatenate – (lo abbiamo visto qualche puntata fa) ma in maniera più intelligente. Faccio prima alcuni esempi:

– primo esempio. Visualizzare il file cosi’ com’e’:

bottega@bottegadelbarbieri  ~  sed -n 'p' the-rhyme-of-the-ancient-mariner.txt |head -n 20
PART THE FIRST.
     It is an ancient Mariner,
     And he stoppeth one of three.
     "By thy long grey beard and glittering eye,
     Now wherefore stopp'st thou me?

     "The Bridegroom's doors are opened wide,
     And I am next of kin;
     The guests are met, the feast is set:
     May'st hear the merry din."

     He holds him with his skinny hand,
     "There was a ship," quoth he.
     "Hold off! unhand me, grey-beard loon!"
     Eftsoons his hand dropt he.

     He holds him with his glittering eye--
     The Wedding-Guest stood still,
     And listens like a three years child:

– secondo esempio. Visualizzare tutte le linee per due volte:

bottega@bottegadelbarbieri  ~  sed 'p' the-rhyme-of-the-ancient-mariner.txt |head -n 20
PART THE FIRST.
PART THE FIRST.

     It is an ancient Mariner,
     It is an ancient Mariner,
     And he stoppeth one of three.
     And he stoppeth one of three.
     "By thy long grey beard and glittering eye,
     "By thy long grey beard and glittering eye,
     Now wherefore stopp'st thou me?
     Now wherefore stopp'st thou me?


     "The Bridegroom's doors are opened wide,
     "The Bridegroom's doors are opened wide,
     And I am next of kin;
     And I am next of kin;
     The guests are met, the feast is set:
     The guests are met, the feast is set:

– terzo esempio. Visualizzare soltanto alcune linee (dalla 20 alla 35):

bottega@bottegadelbarbieri  ~  sed -n '20,35p'  the-rhyme-of-the-ancient-mariner.txt 
     And listens like a three years child:
     The Mariner hath his will.

     The Wedding-Guest sat on a stone:
     He cannot chuse but hear;
     And thus spake on that ancient man,
     The bright-eyed Mariner.

     The ship was cheered, the harbour cleared,
     Merrily did we drop
     Below the kirk, below the hill,
     Below the light-house top.

     The Sun came up upon the left,
     Out of the sea came he!
     And he shone bright, and on the right

Questo comando può essere molto interessante se vogliamo, per esempio, combinare alcune funzioni con altre. Se per ipotesi volessi inserire il simbolo cancelletto # all’inizio o alla fine delle linee dalla 20 alla 35:

bottega@bottegadelbarbieri  ~  sed -n '20,35p'  the-rhyme-of-the-ancient-mariner.txt | sed 's/^/# /'
#      And listens like a three years child:
#      The Mariner hath his will.
# 
#      The Wedding-Guest sat on a stone:
#      He cannot chuse but hear;
#      And thus spake on that ancient man,
#      The bright-eyed Mariner.
# 
#      The ship was cheered, the harbour cleared,
#      Merrily did we drop
#      Below the kirk, below the hill,
#      Below the light-house top.
# 
#      The Sun came up upon the left,
#      Out of the sea came he!
#      And he shone bright, and on the right

bottega@bottegadelbarbieri  ~  sed -n '20,35p'  the-rhyme-of-the-ancient-mariner.txt | sed 's/$/# /'
     And listens like a three years child:# 
     The Mariner hath his will.# 
 
     The Wedding-Guest sat on a stone:# 
     He cannot chuse but hear;# 
     And thus spake on that ancient man,# 
     The bright-eyed Mariner.# 
 
     The ship was cheered, the harbour cleared,# 
     Merrily did we drop# 
     Below the kirk, below the hill,# 
     Below the light-house top.# 
 
     The Sun came up upon the left,# 
     Out of the sea came he!# 
     And he shone bright, and on the right# 

Come avete visto, qui abbiamo utilizzato un’altra espressione regolare, il pipe | che ci permette di combinare più comandi allo stesso tempo. Interessante vero?

-n ‘nd’ – delete numbered lines –
Lavoriamo ora sulla nostra copia del file, cerchiamo di rimuovere le linee che vanno dalla 20 alla 35. Invece che usare il parametro p (print) utilizzeremo il parametro d (delete). Dunque prima visualizziamo il file, poi rimuoviamo le linee, e ri-visualizziamo il fie per vedere cosa è cambiato:

bottega@bottegadelbarbieri  ~  sed -n '20,35p'  the-rhyme-of-the-ancient-mariner_copy.txt 
     And listens like a three years child:
     The Mariner hath his will.

     The Wedding-Guest sat on a stone:
     He cannot chuse but hear;
     And thus spake on that ancient man,
     The bright-eyed Mariner.

     The ship was cheered, the harbour cleared,
     Merrily did we drop
     Below the kirk, below the hill,
     Below the light-house top.

     The Sun came up upon the left,
     Out of the sea came he!
     And he shone bright, and on the right

bottega@bottegadelbarbieri  ~  sed '20~35d'  the-rhyme-of-the-ancient-mariner_copy.txt > the-rhyme-of-the-ancient-mariner_copy1.txt

bottega@bottegadelbarbieri  ~  sed -n '20,35p'  the-rhyme-of-the-ancient-mariner_copy1.txt 
     The Mariner hath his will.

     The Wedding-Guest sat on a stone:
     He cannot chuse but hear;
     And thus spake on that ancient man,
     The bright-eyed Mariner.

     The ship was cheered, the harbour cleared,
     Merrily did we drop
     Below the kirk, below the hill,
     Below the light-house top.

     The Sun came up upon the left,
     Out of the sea came he!
     And he shone bright, and on the right
     Went down into the sea.

Ed ecco qui che abbiamo inserito un altro simbolo che abbiamo già incontrato nel passato, il > che stampa lo stdout in un nuovo file, per evitare (si sa, prevenire è meglio che curare) errori di sorta.

La lista ovviamente non si conclude qui. Se volete esplorare altre opzioni, vi invito leggere il manuale (abbiamo dedicato una intera puntata a come leggerlo, ricordate?). E poi, che dire, tante care cose come si dice dalle mie parti e… Continuate a mettere la mascherina, che le varianti son sempre in agguato.

Alla prossima settimana!
jolek78

>> Indice <<
Puntata 24 < > Puntata 26

Il logo “Tux Linux” e’ stato realizzato e distribuito dall’artista deiby-ybied su Deviantart in licenza Creative Commons BY-NC-SA 3.0

jolek78 on Email
jolek78
Un tizio che pensava di essere uno scienziato. Si ritrovò divulgatore scientifico. Poi si addormentò su un aereo e si risvegliò informatico. Ma era sempre lui.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *