AWK_Doc

AWK acronyme de (Aho, Weinberger and Kernighan)

  • WIKI - Qu'est ce AWK ?
  • Un condensé des commandes en PDF (From www.catonmat.net)
  • Un condensé des commandes en TXT
  • Page man de AWK
  • Une synthèse de la commande AWK
  • Autre synthèse de la commande AWK
  • Good examples AWK
  • Exemples
    • Les principales fonctions pour traiter les chaines de caractères
    • 
      
      Nom des fonctions signification
      gsub(r,s,t) sur la chaine t, remplace toutes les occurance de r par s
      sub(r,s,t) comme gsub, mais remplace uniquement la première occurence
      index(s,t) retourne la position la plus à gauche de la chaine t dans la chaine s
      length(s) retourne la longueur de la chaine s
      match(s,r) retourne l'index ou s correspond à r et positionne RSTART et RLENTH
      split(s,a,fs) split s dans le tableau a sur fs, retourne le nombre de champs
      sprintf(fmt,liste expressions) retourne la liste des expressions formattée suivant fmt
      substr(s,i,n) retourne la sous chaine de s commencant en i et de taille n
    • Affiche lignes du fichier en entrée dès rencontre chaîne debut et jusqu'à chaîne fin ou EOF
    • 
      shell>  awk '/debut/,/fin/' regle.awk
      #----------- marge debut
           imarge=ARGV[2];
           marge="" ;
           if ( imarge != "" ) { for ( ;imarge > 0; imarge-- ) { marge=marge" " } }
      #----------- plus info en fin de regle
      
    • Changer valeur sur une colonne de la ligne
    • 
      shell> echo '1456 E 17-oct-2016 FIFABRMIMA05 CSARSENE L0006DI7 TERMINE EAIE.U00PM00.CSARSENE.TSRI03ME.J1701253.N0 FICHIER RSA CNAF ' | \
       awk '{ for ( i=1;i<NF;i++) { if (match($i,"P00") || match($i,"L00")) { gsub($i,"<a href= ..>"$i"</a>",$i) }} ; print $0 }'
      
      shell> 1458 E 17-oct-2016 FIFABRMIMA05 CSARSENE <a href= ..>L0006DI7</a> TERMINE EAIE.U00PM00.CSARSENE.TSRI03ME.J1701253.N0 FICHIER RSA CNAF
      
      
    • Divers et très utiles
    • 
      voir site Good examples AWK
      
      
    • Comme sort -u
    • shell> awk -F',' '{a[$1];}END{for (i in a)print i;}' file shell> awk -F, '!a[$2]++' file
    • Total par colonne et reference
    • shell> awk -F, '{a[$1]+=$2;}END{for(i in a)print i", "a[i];}' file toto,100 titi,200 titi,500 => toto,100 titi,700
    • Different separateur dans fichier en entree et choix d'un separateur en sortie
    • shell> awk -F '[:,]' '{a[$1]++;}END{for (i in a)print i, a[i];}' OFS=':' file toto,100 titi:200 titi,500 => toto:100 titi:700
    • Total sur une colonne donnée
    • shell> awk -F"," '{x+=$2;print}END{print "Total,"x}' file => Total, 800
    • Nombre d'occurrences sur une colonne donnée
    • shell> awk -F, '{a[$1]++;}END{for (i in a)print i, a[i];}' file toto,100 titi,200 titi,500 => toto:1 titi:2
    • Affiche lignes contenant la chaîne nom
    • 
      shell>  ps -ef | awk '/nom/'
      
    • Test or || et &&
    • 
      shell>  if ( $2 ~ /toto/ || $2 ~ /tutu/ ) {   ...   }
      shell>  if ( $2 ~ /toto/ && $2 ~ /tutu/ ) {   ...   }
      
      
    • Lire un fichier à partir d'un enregistrement jusqu'à un autre
      • Script à definir dans un fichier
      • #!/bin/ksh LIGDEB=1 LIGFIN=100 FICHIER=fichier_a_traiter awk 'BEGIN { LIGDEB=ENVIRON["LIGDEB"] ; LIGFIN=ENVIRON["LIGFIN"] ; } (NR==LIGDEB),(NR==LIGFIN) {print} ; (NR==LIGFIN) {exit 0} ; ' ${FICHIER}
      • Commande online
      • shell> awk '(NR==1),(NR==3) {print} ' ${FICHIER}
      • Commande online de la ligne 10 a 24
      • shell> awk 'NR >= 10 && NR <= 24{print} ' ${FICHIER} shell> awk 'BEGIN{} NR>=10&&NR<=24{print NR } END{}' ${FICHIER}
      • Commande online que les lignes 10 à 24
      • shell> awk 'BEGIN{} NR==10||NR==24{print NR } END{}' ${FICHIER}
      • Commande online toutes sauf les lignes 10 à 24
      • shell> awk 'BEGIN{} !(NR>=10&&NR<=24) {print NR } END{}' ${FICHIER}
    • Formater un fichier non structuré suivant une longueur donnée
      (idem cde fold - wrap each input line to fit in specified width- )
    • awk '{ ch=$0 ; for ( i=1 ; i<length(ch) ; i=i+128 ) { printf("%-9i %-9s %-9i %-s\n",NR,length(ch),i,substr(ch,i,128) ) } }' Fic
      
    • Creer directives sql insert d'après un fichier ayant les données separarées par #
    • 
      #-----------------------------------------------------
      # Mettre en table fichier table_routage_helios
      #-----------------------------------------------------
      #
      #
      #----- vider la table avant les inserts
      #----- ne pas prendre en compte les commentaires dans le fichier débutants par #
      awk 'BEGIN {print "TRUNCATE TABLE tab_routage;" } !/^#/ {
      
      #----- recuperer les champs séparés par # dans la table t
            split($0,t,"#")
      
      #----- debut de chaque insert à élaborer
            printf("INSERT INTO tab_routage VALUES (");
      
      #----- Nombre de colonnes de la table 
            MaxCh=14
      
      #----- Constituer les valeurs des colonnes de la table
            for ( j=1;j<=MaxCh ; j++ ) {
                 sep=","
                 if ( j == MaxCh ) sep="";
      
      #----- preserver les virgules sur données lues les bornées par \,
                 gsub(",","\\,",t[j])
      #----- preserver les quotes sur données lues les bornées par \'
                 gsub("'\''","\\'\''",t[j])
      
      #----- ecrire champ
                 printf("'\''%s\'\''%s",t[j],sep)
            }
      #----- fin de ligne pour chaque insert constitué
             printf(");\n")
      
      }' Fic
      
      
    • Tableaux associatifs
    • 
      #!/bin/sh
      #
      # to see many fic in /environnements/PROD/production/csgflawr/reception
      #   IDF an his heading
      #
      
      set -a 
      
      FicTmp=/cygdrive/c/temp/temp_$$
      
      # etat sas reception EAI
      
      ssh -t user@host 'df -g /environnements/PROD/production/csgflawr/reception/' | awk '{ print ; if ($0 ~ "/FS_NFS_SASSGF" ) tot=$2-$3 ; } END { print "Total utilisé en Go : "tot }' > ${FicTmp}
      ssh -t user@host 'find /environnements/PROD/production/csgflawr/reception/ -type f -exec head -n 1 {} + | cut -c1-100 ' > ${FicTmp}_
      echo -e
      cat ${FicTmp}
      echo -e
      
      awk 'BEGIN {
         tot=0 ;
         print "   +++++++++++++++++++++++++++++++++++++++++++++++++++" ; 
         printf("     %s | %-15s | %-10s | %10s \n","Num","Idf","  Id   Si","Nbre");
         print "   +++++++++++++++++++++++++++++++++++++++++++++++++++" ;
      }'
       grep ^DDF  ${FicTmp}_ | awk '{
       idf=substr($1,6,8);
       id=substr($0,22,4);
       si=substr($0,26,2);
      #--------- cle du tableau avec elements associatif dans ce cas trois variables
       nom=idf""id""si ;
      #--------- ajouter cle au tableau
       if ( nom != rnom ) {rnom=nom;tnom[rnom]++ } ;
      #--------- ajouter des colonnes de valeurs a la cle
       tidf[rnom]=idf ;tid[rnom]=id;tsi[rnom]=si;++tnbr[rnom] ;
      }
      END {
      #--------- editer le tableau
        for (lnom in tnom) 
       { i++ ; printf(" | %-15s |  %-4s  %-2s  | %10s \n",tidf[lnom],tid[lnom],tsi[lnom],tnbr[lnom] ) > "/cygdrive/c/temp/temp_9999__" ; tot=tot+tnbr[lnom] ; }
         printf("     Total %s %i\n",substr("                                          ",1,40-length(tot)),tot) > "/cygdrive/c/temp/temp_9999___" ;
      }' 
      
      sort -t'|' -k2.1,2.8 -k3.1,3.7 /cygdrive/c/temp/temp_9999__ | cat -n
      cat /cygdrive/c/temp/temp_9999___
      
      
  • Tableau colonnes 1er ligne fichier lu
  • 
    #!/bin/sh
    ##############################################
    #
    # to creat send with model CFTUTIL and xml desc of display
    #
    ##############################################
    #
    ## . ~/.bash_profile
    
    ##  sort -t' ' -k1,2 - |sed '1,19d'|grep -v "Pour generer"|awk '{ if (NR==1){ Npa=split($0,a," "); for (i=0;i<=Npa;i++){a[i]=toupper(a[i])} ; next } ;
    ###  sort -t' ' -k1,2 - |sed '1,18d'|awk '{ if (NR==1){ Npa=split($0,a," "); for (i=0;i<=Npa;i++){a[i]=toupper(a[i])} ; next } ;
     sort -t' ' -k1,2 - |sed '1,18d'|awk '{ if (NR==1){ toupper($0) ; Npa=split($0,a," ");split($0,c," "); for (i=0;i<=Npa;i++){ c[i]=match($0,a[i]);a[i]=toupper(a[i])} ; next } ;
    ###   Npb=split($0,b," "); if ( Npb -ne Npa ) { print "#####AVERTISSEMENT##### Manque valeur pour une ou des colonnes" };
         Npb=split($0,b," ");
      printf("CFTUTIL send type=file, \\\n");
      j=0; for (i=1;i<=Npa;i++) 
      { j=j+1 ; 
       if ( substr($0,c[i],1)==" " ) {  printf("        %s=###Manque valeur colonne### %s\n",a[i],sep) ; i=i+1 ; loop } ;
       if ( substr($0,c[i],1)=="-" ) {  b[j]="" } ;
       sep="";if (i<Npa){sep=", \\"} ; 
       if ( a[i]=="STATE" ) { gsub("X","Disp",b[j]) ; gsub("H","Hold",b[j])  } ;
       if ( a[i]=="FCODE" ) { gsub("A","Ascii",b[j]) ; gsub("B","Binary",b[j]) } ;
       if ( a[i]=="PARM" ) {printf("        %s=\"'\''%s'\''\" %s\n",a[i],b[j],sep) } else { printf("        %s=%s %s\n",a[i],b[j],sep)} ; 
       if ( a[i]=="FLRECL" ) { FLRECL=b[j] } ;
       if ( a[i]=="FNAME" ) { if ( b[j] ~  "/cftdata/CFT/EAIE" ) 
          { printf("#ToRetFname# dsmc ret -verbose -replace=no /apps/data/CFT/REEL/CFT/EAI_CFTE.%s.L%06i.FFB %s\n",substr(b[j],19),FLRECL,b[j]) }
          else
          { printf("#####ToRetFname# dsmc ret -verbose -replace=no /apps/data/CFT/REEL/CFT/%s\n",substr(b[j],14)) }} ;
      }
      print " ";
    }' |egrep -v "NREC=|TREC=|DIAGI=|FDATE=|FTIME=|DATEE=|SENS=|IDT="
    
    exit
    
    ################### le xml associer a l'appel CFTUTIL : CFTDSPCNF=/tmp/dspcnfsendfic.xml CFTUTIL display type=file,state=h
    ##########
    
    <?xml content='ascii'?>
    
    <!-- Filter Model for the CFTUTIL DISPLAY command
    CFTUTIL DISPLAY  
    		listcat-parameters
                    + content= | STR                <- nothing means first available
    		+ fmodel = DSPCNF | STR         <- DSPCNF is system dependant : ex.: UNIX/Windows is DSPCNF an environment variable
    		+ mode   = ANY | column | line  <- ANY means use the model's
    		+ na     = ANY | STR            <- idem
    		+ empty  = ANY | STR            <- idem
    		+ help   = NONE | FIELDS | MODELS 
    		
    <CFTDisplayFilter
    	id='STR'
    	mode            = 'column|line'
    	title_size      = '-1|NUM'              <- apply only in line mode
    	title_align     = 'left|center|right'   <- apply only in line mode
    	line_prefix     = '|STR'
    	line_suffix     = '\n|STR'
    	default_prefix  = '|STR'
    	default_suffix  = ' |\n|STR'            <- default is ' ' in column mode and '\n' in line mode
    	default_empty   = '-|STR'
    	default_na      = '#|STR'
    	>
    	<Fields>
    		<Field 	id        = 'ID' 
    				title     = 'id|STR'   <- default uses the id for the title name
    				maxlength = '-1|NUM'   <- default(-1) means that no length is used
    				minlength = '-1|NUM'  
    				prefix    = '|STR' 
    				suffix    = '|STR' 
    				align     = 'left|center|right'
    				na        = '|STR'
    				empty     = '|STR' 
    		/>
    	<Fields>
    <CFTDisplayFilter>
    -->
    
    <!-- LISTCAT Model : classical CFTUTIL LISTCAT with long IDs -->
    <CFTDisplayFilter 	id		='listcat'
    			title_align  	='left' >
    	<Fields>
    <Field id='PART'                  title='PART' />
    <Field id='IDF'		title='IDF'		minlength='4' />
    <Field id='NIDF'		title='NIDF'		minlength='4' />
    <Field id='DIRECT'	title='Sens'	/>
    <Field id='STATE'	title='State' align='left' />
    <Field id='IDT'                   title='IDT' />
    <Field id='FREC'	title='Nrec'	align='left' />
    <Field id='NREC'                  title='Trec' align='left' />
    <Field id='DATEE'                  title='Datee' />
    <Field id='FTYPE'                 title='FTYPE' align='left' />
    <Field id='FCODE'                 title='FCODE' align='left' />
    <Field id='FRECFM'                title='FRECFM' align='left' />
    <Field id='FLRECL'                title='FLRECL' align='left' />
    <Field id='SUSER'       title='Suser' maxlength='8'     />
    <Field id='RUSER'       title='Ruser' maxlength='8'     />
    <Field id='PARM'                  title='Parm' />
    <Field id='IDA'                   title='Ida' />
    <Field id='FNAME'                 title='FNAME' />
    
    	</Fields>
    </CFTDisplayFilter>
    
    
    

Exemple de AWK

  • Le source de regle.awk
  • Exemple de rendus
    1. Afficher une règle dans un terminal
      user@user:~$ awk -f ./regle.awk 101
              10        20        30        40        50        60        70        80        90        100
      ----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|
      
    2. Placer le début de la règle à partir de la colonne 10
      user@user:~$ awk -f ./regle.awk 91 10
                        10        20        30        40        50        60        70        80        90
                ----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|
      
    3. En cas de depassement ou pour signaler une valeur max
      user@user:~$ awk -f ./regle.awk 80 10 300
                        10        20        30        40        50        60        70        80     300
                ----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|......|
      
    4. Pour situer la règle apres PS1
      user@user:~$ awk -f ./regle.awk 81 $( expr ${#PS1} + ${#PWD} - 5 )
                           10        20        30        40        50        60        70        80
                   ----+----|----+----|----+----|----+----|----+----|----+----|----+----|----+----|
      
      

Exemple de AWK résultat de la commande cal ( calendar ) en html

  • source
  • Exemple de rendu
  • De la commande Linux ou AIX

  • 
    user@user:~$ cal 05 2013
          Mai 2013
    lu ma me je ve sa di
           1  2  3  4  5
     6  7  8  9 10 11 12
    13 14 15 16 17 18 19
    20 21 22 23 24 25 26
    27 28 29 30 31
    
    
  • On aura ça

  • Mai 2013
    Dim Lun Mar Mer Jeu Ven Sam
    1234
    567891011
    12131415161718
    19202122232425
    262728293031
  • Le php pour lancer ce AWK à partir d'un navigateur web


Previous page: Scripts pour Gestion TSM
Page suivante : Sed