MagPI 12 Page 32

De Le French MagPi
(Différences entre les versions)
Aller à : Navigation, rechercher
(Scinder des lignes en entrée)
Ligne 71 : Ligne 71 :
 
   done
 
   done
 
   echo ""
 
   echo ""
  done < input_file.txt
+
done < input_file.txt
  
  

Version du 23 juin 2013 à 08:54

Sommaire

2 - Textes et programmes embarqués

DIFFICULTÉ : MOYENNE


Solution du défi

Comment vous en êtes-vous sorti avec le problème du Numéro 10 ? En voici une solution :

#!/bin/bash
# Un script pour gzipper tous les fichiers du répertoire
# de travail actuel. Il exclut les fichiers gzip qui se
# terminent par .gz.
for file in $(find $PWD -maxdepth 1 -type f | grep -v . gz); do 
  gzip $file
done


Bash (Bourne Again Shell) fournit beaucoup de fonctionnalités, mais l'un de ses points forts est la façon dont d'autres programmes ou langages de scripts peuvent lui être liés pour produire une application finale.

Fichiers embarqués

Open a terminal window and use the nano editor mentioned within the last tutorial session. Then create a new script file containing,


#!/bin/bash
cat > input_file.txt <<EOF
ColumnA_row1 ColumnB_row1 ColumnC_row1 ColumnD_row1
ColumnA_row2 ColumnB_row2 ColumnC_row2 ColumnD_row2

ColumnA_row3 ColumnB_row3 ColumnC_row3 ColumnD_row3
ColumnA_row4 ColumnB_row4 ColumnC_row4 ColumnD_row4
EOF


save it and make it executable ( chmod u+x scri pt. sh ). Execute the script and look at the i nput_fi l e. txt that it produces. The i nput_fi l e. txt matches the text given between the <<EOF and EOF statements. For this script to work, there must not be a space after <<EOF . The syntax of the script states that the text following <<EOF is redirected to the file i nput_fi l e. txt until EOF is reached. The redirect operator ( >) works in the same way as mentioned in the last tutorial, truncating the output file and then appends to it. The <<EOF syntax can be very helpful for embedding parts of configuration files within a script, rather than using many echo commands.

Scinder des lignes en entrée

If a file is read using a standard for loop, then each word (separated by one or more spaces) becomes a value within the loop. This can be helpful for some problems, but the line number information is lost. The read command provides a solution,


#!/bin/bash
while read line; do
  for word in $line; do
    echo -n "$word "
  done
  echo ""
done < input_file.txt


In this example, the outer loop reads each line of the file into the variable $l i ne . Then in the inner loop, each word within a line is considered by the for loop. The -n in the echo command means that echo does not add a newline character after printing the line. The input file is associated with the whi l e loop by using input redirection ( <).

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Boîte à outils