[Script] Tester l'extension d'un fichier

korian -  
 korian -
Bonjour,
Je suis débutant donc soyez indulgent svp.

Je parcours un répertoire dans une boucle et récupère le nom des fichiers un par un dans une variable i.
Comment tester que i contient l'extension txt ?
Je suis en shell sh.

#!/bin/sh
# Déclaration des variables
NbFic=0
NbFicTxt=0
# Boucle sur tous les fichiers (ignore les erreurs)
for i in `find . -type f -name '*' 2>/dev/null`
do
	# Compte tous les fichiers non répertoire
	NbFic=`expr $NbFic + 1`;

	if  ????????????  $i et txt ????????;
	then
		# Compte tous les fichiers .txt
		NbFicTxt=`expr $NbFicTxt + 1`;
	fi
		
done


Merci d'avance pour les réponses.
Configuration: Windows XP
Safari 532.0

6 réponses

  1. jipicy Messages postés 40842 Date d'inscription   Statut Modérateur Dernière intervention   4 898
     
    Salut,

    [tmpfs]$ var="fichier.txt"
    
    [tmpfs]$ echo ${var}
    fichier.txt
    
    [tmpfs]$ echo ${var##*.}
    txt
    
    [tmpfs]$

    Donc :

    if [ "${var##*.}" = "txt" ]; then...


    ;-))
    1
  2. lami20j Messages postés 21506 Date d'inscription   Statut Modérateur, Contributeur sécurité Dernière intervention   3 571
     
    Salut,

    # Compte tous les fichiers .txt
    Et comme ça, ce n'est pas bon?

    $ nbrtxt=$(find ./trash2 -type f -name '*.txt' 2>/dev/null| wc -l)
    $ echo $nbrtxt
    6


    0
  3. korian
     
    Merci pour vos réponses rapides, j'apprécie. J'ai du laisser passer le WE pour les tester :)
    @jipicy : la chaine déclenche une erreur : substitution incorrecte. Es tu sur de la syntaxe pour un shell sh ?
    @lami20j : je souhaite exécuter un traitement sur chaque fichier et un particulier sur les txt et pas seulement les compter.
    0
  4. jipicy Messages postés 40842 Date d'inscription   Statut Modérateur Dernière intervention   4 898
     
    Re-

    Normalement il ne devrait pas y avoir de problème ;-\

    Pour la commande de lami20j, il suffit de rajouter le paramètre "-exec" suivi de la commande adéquate... par exemple :

    find ./trash2 -type f -name '*.txt' -exec stat -c '%n : %A' {} \;

    ou encore avec "xargs" :

    find ./trash2 -type f -name '*.txt' | xargs stat-c '%n : %A


    Quel genre de traitement dois-tu exécuter sur chaque fichier ?
    0
  5. Vous n’avez pas trouvé la réponse que vous recherchez ?

    Posez votre question
  6. korian
     
    Re,
    Comment fonctionne ton masque ? car je n'arrive pas à trouver d'exemple dans mon bouquin sur les scripts. Les caractères génériques sont * ou ? pour moi et à priori pas d'utilisation de {}.

    Quand aux traitements, j'aimerais faire un grep et un sed.

    Merci pour l'aide.
    0
    1. jipicy Messages postés 40842 Date d'inscription   Statut Modérateur Dernière intervention   4 898
       
      Ouvre la page de man de sh et cherche "Parameter Expansion" :

      Parameter Expansion
           The format for parameter expansion is as follows:
      
      	   ${expression}
      
           where expression consists of all characters until the matching `}'.  Any
           `}' escaped by a backslash or within a quoted string, and characters in
           embedded arithmetic expansions, command substitutions, and variable
           expansions, are not examined in determining the matching `}'.
      
           The simplest form for parameter expansion is:
      
      	   ${parameter}
      
           The value, if any, of parameter is substituted.
      
           The parameter name or symbol can be enclosed in braces, which are
           optional except for positional parameters with more than one digit or
           when parameter is followed by a character that could be interpreted as
           part of the name.	If a parameter expansion occurs inside double-quotes:
      
           1.   Pathname expansion is not performed on the results of the expansion.
      
           2.   Field splitting is not performed on the results of the expansion,
      	  with the exception of the special parameter @.
      
           In addition, a parameter expansion can be modified by using one of the
           following formats.
      
           ${parameter:-word}
      	     Use Default Values.  If parameter is unset or null, the expansion
      	     of word is substituted; otherwise, the value of parameter is sub-
      	     stituted.
      
           ${parameter:=word}
      	     Assign Default Values.  If parameter is unset or null, the expan-
      	     sion of word is assigned to parameter.  In all cases, the final
      	     value of parameter is substituted.  Only variables, not posi-
      	     tional parameters or special parameters, can be assigned in this
      	     way.
      
           ${parameter:?[word]}
      	     Indicate Error if Null or Unset.  If parameter is unset or null,
      	     the expansion of word (or a message indicating it is unset if
      	     word is omitted) is written to standard error and the shell exits
      	     with a nonzero exit status.  Otherwise, the value of parameter is
      	     substituted.  An interactive shell need not exit.
      
           ${parameter:+word}
      	     Use Alternate Value.  If parameter is unset or null, null is sub-
      	     stituted; otherwise, the expansion of word is substituted.
      
           In the parameter expansions shown previously, use of the colon in the
           format results in a test for a parameter that is unset or null; omission
           of the colon results in a test for a parameter that is only unset.
      
           ${#parameter}
      	     String Length.  The length in characters of the value of
      	     parameter.
      
           The following four varieties of parameter expansion provide for substring
           processing.  In each case, pattern matching notation (see Shell
           Patterns), rather than regular expression notation, is used to evaluate
           the patterns.  If parameter is one of the special parameters * or @, the
           result of the expansion is unspecified.  Enclosing the full parameter
           expansion string in double-quotes does not cause the following four vari-
           eties of pattern characters to be quoted, whereas quoting characters
           within the braces has this effect.
      
           ${parameter%word}
      	     Remove Smallest Suffix Pattern.  The word is expanded to produce
      	     a pattern.  The parameter expansion then results in parameter,
      	     with the smallest portion of the suffix matched by the pattern
      	     deleted.
      
           ${parameter%%word}
      	     Remove Largest Suffix Pattern.  The word is expanded to produce a
      	     pattern.  The parameter expansion then results in parameter, with
      	     the largest portion of the suffix matched by the pattern deleted.
      
           ${parameter#word}
      	     Remove Smallest Prefix Pattern.  The word is expanded to produce
      	     a pattern.  The parameter expansion then results in parameter,
      	     with the smallest portion of the prefix matched by the pattern
      	     deleted.
      
           ${parameter##word}
      	     Remove Largest Prefix Pattern.  The word is expanded to produce a
      	     pattern.  The parameter expansion then results in parameter, with
      	     the largest portion of the prefix matched by the pattern deleted.
      


      Quand a ton traitement, l'expression initiée par lami20j me parait la plus adaptée en remplaçant "wc" par "sed" (qui regroupe les fonctionnalités de "grep")...
      0
  7. korian
     
    Ok merci pour l'extraction man :) C'est là que je vois que je n'ai pas encore les bons reflexes unix.
    La solution de lami20j semble effectivement plus efficae en travaillant sur des ensembles plutot que sur une revue 1 par 1 mais je voulais faire une imbrication de if fi pour tester. donc je veux d'avbord faire marcher avec test et ensuite je le modifierais pour optimiser.
    Je vais continuer avec ton ## et je te tiens au courant.
    Merci pour l'aide en tout cas.
    0