[Test] Probar la extensión de un archivo

korian -  
 korian -
Hola,
Soy principiante, así que por favor sé indulgente.

Estoy recorriendo un directorio en un bucle y recupero el nombre de los archivos uno por uno en una variable i.
¿Cómo probar si i contiene la extensión txt?
Estoy en shell sh.

#!/bin/sh # Declaración de variables NbFic=0 NbFicTxt=0 # Bucle sobre todos los archivos (ignorar errores) for i in `find . -type f -name '*' 2>/dev/null` do # Cuenta todos los archivos que no son directorios NbFic=`expr $NbFic + 1`; if ???????????? $i y txt ????????; then # Cuenta los archivos .txt NbFicTxt=`expr $NbFicTxt + 1`; fi done


Gracias de antemano por las respuestas.
Configuración: Windows XP Safari 532.0

6 respuestas

  1. jipicy Mensajes publicados 40842 Fecha de registro   Estado Moderador Última intervención   4 898
     
    Hola,

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

    Entonces :

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


    -))
    --
    $ man woman
    No hay ninguna página de manual para woman.
    1
  2. lami20j Mensajes publicados 21506 Fecha de registro   Estado Moderador, Colaborador de seguridad Última intervención   3 571
     
    Hola,

    # Cuenta todos los archivos .txt
    Y así, ¿no está bien?

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


    --
    106485010510997108
    0
  3. korian
     
    Gracias por tus respuestas rápidas, las aprecio. Tuve que dejar pasar el fin de semana para probarlas :)
    @jipicy : la cadena genera un error: sustitución incorrecta. ¿Estás seguro de la sintaxis para un shell sh?
    @lami20j : quiero ejecutar un procesamiento en cada archivo y uno particular en los txt y no solo contarlos.
    0
  4. jipicy Mensajes publicados 40842 Fecha de registro   Estado Moderador Última intervención   4 898
     
    Re-

    Normalmente no debería haber ningún problema ;-\

    Para el comando de lami20j, basta añadir el parámetro ""-exec"" seguido del comando adecuado... por ejemplo:

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

    o también con ""xargs"" :

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


    ¿Qué tipo de procesamiento debes ejecutar sobre cada archivo?

    --
    $ man woman
    No existe una página de manual para woman.
    0
  5. korian
     
    Hola,
    ¿Cómo funciona tu máscara? porque no consigo encontrar ningún ejemplo en mi libro sobre los scripts. ¿Los comodines son * o ? para mí y, al parecer, no se usa {}.

    En cuanto a los métodos, me gustaría hacer un grep y un sed.

    Gracias por la ayuda.
    0
    1. jipicy Mensajes publicados 40842 Fecha de registro   Estado Moderador Última intervención   4 898
       
      Abre la página del manual de sh y busca "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. 


      Cuando llegue a tu tratamiento, la expresión iniciada por lami20j me parece la más adecuada reemplazando "wc" por "sed" (que agrupa las funciones de "grep")...

      --
      $ man woman
      No existe la entrada del manual para woman.
      0
  6. korian
     
    Gracias por la extracción manual :) Es entonces cuando veo que aún no tengo los reflejos correctos de Unix.
    La solución de lami20j parece efectivamente más eficiente trabajando con conjuntos en lugar de una revisión 1 por 1, pero quería hacer una anidación de if fi para probar. así que quiero primero hacer que funcione con test y luego lo modificaría para optimizar.
    Voy a continuar con tu ## y te mantendré informado.
    Gracias por la ayuda, en cualquier caso.
    0