Creation: 19 mai 2014
Mise à jour: Version: 1.1
Author: Jean-Louis Bicquelet-Salaün
Location: http://jlbicquelet.free.fr
Copyright: (c) 2014 Jean-Louis BICQUELET
Awk exemples simples et cours
Awk est un langage puissant. Il est par contre difficile à maintriser et à retenir.
J'avais déjà fait une page sur le sujet. J'ai décidé d'en refaire une sous forme de quicksheet, organisée sous forme de catégorie, pour faciliter la recherche d'exemples.
manipulation de chaines
mise en minuscule |
<commande> | awk '{ print tolower ($0) }'
|
mise en majuscule |
<commande> | awk '{ print toupper ($0) }'
|
substitution de chaine |
<commande> | awk '{ gsub(/ABC/, "XYZ"); print '
|
affiche le dernier caractère |
<commande> | awk '{print substr($1,length($1),1)}
|
Mise en forme de timestamp |
errpt |grep hdisk21 | awk '{ printf ("%s:%s\n",substr($2,5,2),substr($2,7,2)) }'
|
substitution de tous les patterns |
awk '{ gsub(/Britain/, "United Kingdom"); print '
|
Exemples
echo "toto" |awk '{ print tolower ($0) }'
toto
#echo "toto" |awk '{ print toupper ($0) }'
TOTO
errpt | awk 'NR==1, NR==10'
IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION
DCB47997 0402112514 T H hdisk10 DISK OPERATION ERROR
DCB47997 0402073514 T H hdisk21 DISK OPERATION ERROR
DCB47997 0402072314 T H hdisk11 DISK OPERATION ERROR
DCB47997 0401172714 T H hdisk11 DISK OPERATION ERROR
DCB47997 0401160714 T H hdisk11 DISK OPERATION ERROR
DCB47997 0401155614 T H hdisk11 DISK OPERATION ERROR
DCB47997 0401013414 T H hdisk12 DISK OPERATION ERROR
DCB47997 0331175814 T H hdisk8 DISK OPERATION ERROR
DCB47997 0331172614 T H hdisk8 DISK OPERATION ERROR
manipulation de fichier
grep |
<commande> | awk '/string/'
|
wc -l |
<commande> | awk 'END{print NR}'
|
head |
<commande> | awk 'NR==1, NR==20'
|
tail |
<commande> | awk 'NR==1, NR==20'
|
selectionner une ligne |
<commande> | awk 'NR==13'
|
selection d'un paragraphe |
<commande> | awk '/BEGIN/,/END/'
|
afficher le nombre de caracteres par ligne |
<commande> |awk '{print length}'
|
afficher les lignes de plus de 80 caractères |
<commande> | awk 'length > 80 {printf "%3d. %s\n", NR, $0}'
|
compte le nombre de lignes blanches |
<commande> | awk '/^$/ {x++} END {print x}'
|
exemple:
Pour afficher les ligne 1 et 3:
#errpt |awk 'NR==1 , NR==3'
IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION
A6DF45AA 0401220014 I O RMCdaemon The daemon is started.
A924A5FC 0401215814 P S SYSPROC SOFTWARE PROGRAM ABNORMALLY TERMINATED
colonnes
affiche dans l'ordre inverse |
<commande> | awk '{ for (i = NF; i > 0; --i) print $i }'
|
spliter une ligne |
echo "12:23:11" | awk '{split($0,a,":"); print a[3] a[2] a[1]}'
|
programmation
exemple:
Afficher les caractères de 32 à 127:
awk 'END{for (i=32; i<127; i++) \
printf "%3d %3o %c\n", i,i,i \
}' < /dev/null