Advertisement
GalaxyLJGD

field_search.awk

Apr 24th, 2021
3,052
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Awk 6.01 KB | None | 0 0
  1. #!/usr/bin/awk -f
  2.  
  3. # Copyright © 2021 Neo Galaxy
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are met:
  7. #
  8. # * Redistributions of source code must retain the above copyright notice, this
  9. #   list of conditions and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above copyright notice,
  11. #   this list of conditions and the following disclaimer in the documentation
  12. #   and/or other materials provided with the distribution.
  13. # * Neither the name of the  nor the names of its contributors may be used to
  14. #   endorse or promote products derived from this software without specific
  15. #   prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. # POSSIBILITY OF SUCH DAMAGE.
  28.  
  29. BEGIN {
  30.     RS=""
  31.     FS="\n"
  32.  
  33.     # Muestra el mensaje de ayuda
  34.     if (ARGC == 1)
  35.         help(1)
  36.     if (ARGV[1] == "help")
  37.         help(0)
  38.     # Revisa si hay suficiente argumentos.
  39.     if (ARGC < 4)
  40.         die("Se necesitan al menos tres argumentos")
  41.  
  42.     # Asigna los argumentos de la línea de comandos.
  43.     FIELD = ARGV[1]
  44.     COMPARISON = ARGV[2]
  45.     ARGUMENT = ARGV[3]
  46.  
  47.     if (FIELD == "")
  48.         die("FIELD está vacío")
  49.     else if (COMPARISON == "")
  50.         die("COMPARISON está vacío")
  51.     else if (COMPARISON !~ /^([gl][te]|eq|ne|[!=]=|re|nr)$/)
  52.         die("COMPARISON contiene un argumento inválido")
  53.     else if (ARGUMENT !~ /^[[:digit:]]+$/ && COMPARISON ~ /^([gl][te]|[en]q)$/)
  54.         die("ARGUMENT debe ser un número cuando COMPARISON es gt, ge, lt, " \
  55.             "le, eq o nq")
  56.  
  57.     # Borra los argumentos del script para que AWK no los procese como archivos.
  58.     ARGV[1] = ""
  59.     ARGV[2] = ""
  60.     ARGV[3] = ""
  61.  
  62.     # Una variable para comprobar si ya se ha imprimido.
  63.     prev = 0
  64. }
  65.  
  66. ###
  67. # Imprime un mensaje de error y luego cierra con código 1.
  68. #
  69. # Args:
  70. #    message: mensaje de error a imprimir.
  71. ###
  72. function die(message) {
  73.     printf("ERROR: %s.\n", message) > "/dev/stderr"
  74.     exit 1
  75. }
  76.  
  77. ###
  78. # Imprime el mensaje de ayuda.
  79. #
  80. # Args:
  81. #     code: código de salida después de imprimir el mensaje de ayuda.
  82. ###
  83. function help(code) {
  84.     printf \
  85.         "Uso: field_search.awk [help] FIELD OPERATION ARGUMENT [FILE]...\n" \
  86.         "\n" \
  87.         "Inspecciona archivos en formato desc de Pacman e imprime los \n" \
  88.         "resultados encontrados.\n" \
  89.         "\n" \
  90.         "Argumentos posicionales:\n" \
  91.         "  FIELD       nombre del campo que se inspeccionará.\n" \
  92.         "  COMPARISON  tipo de comparación que se realizará:\n" \
  93.         "                gt: la cantidad de campos es mayor que ARGUMENT.\n" \
  94.         "                ge: la cantidad de campos es mayor o igual que ARGUMENT.\n" \
  95.         "                lt: la cantidad de campos es menor que ARGUMENT.\n" \
  96.         "                le: la cantidad de campos es menor o igual que ARGUMENT.\n" \
  97.         "                eq: la cantidad de campos es igual a ARGUMENT.\n" \
  98.         "                ne: la cantidad de campos no es igual a ARGUMENT.\n" \
  99.         "                ==: el campo es idéntico a ARGUMENT.\n" \
  100.         "                !=: el campo es distinto a ARGUMENT.\n" \
  101.         "                re: el campo coincide con la expresión regular.\n" \
  102.         "                nr: el campo no coincide con la expresión regular.\n" \
  103.         "  ARGUMENT    argumento que se pasará a la operación. No puede \n" \
  104.         "              estar vacío si OPERATION es gt o ge.\n" \
  105.         "  FILE        Archivos que serán procesados.\n" \
  106.         "\n" \
  107.         "Argumentos opcionales:\n" \
  108.         "  help  Muestra este mensaje de ayuda.\n" \
  109.         "\n" \
  110.         "Ejemplos:\n" \
  111.         "  field_search.awk %%DEPENDS%% gt 3 glib2-2.64.3-2/desc\n" \
  112.         "  field_search.awk %%PACKAGER%% re '<.+>' */desc\n"
  113.  
  114.     exit code
  115. }
  116.  
  117. function field_print(f) {
  118.     # Imprime el nombre del archivo si no ha sido impreso antes.
  119.     if (printed == 0) {
  120.         # Imprime una línea nueva antes del nombre del archivo si ya se
  121.         # ha imprimido anteriormente.
  122.         if (prev == 1)
  123.             print ""
  124.         else
  125.             prev = 1
  126.         printf "%s:\n", FILENAME
  127.         printed = 1
  128.     }
  129.     print f
  130. }
  131.  
  132. $1 == FIELD {
  133.     # Se usa para comprobar si ya se imprimió el nombre del archivo.
  134.     printed = 0
  135.     num = NF - 1
  136.  
  137.     if (\
  138.                (COMPARISON == "gt" && num >  ARGUMENT) \
  139.             || (COMPARISON == "ge" && num >= ARGUMENT) \
  140.             || (COMPARISON == "lt" && num <  ARGUMENT) \
  141.             || (COMPARISON == "le" && num <= ARGUMENT) \
  142.             || (COMPARISON == "eq" && num == ARGUMENT) \
  143.             || (COMPARISON == "nq" && num != ARGUMENT) \
  144.     )
  145.         for (i = 2; i <= NF; i++)
  146.             field_print($i)
  147.  
  148.     else
  149.         # Itera sobre cada campo y comprueba si alguno de sus valores cumple con
  150.         # los parámetros dados por el usuario.
  151.         for (i = 2; i <= NF; i++)
  152.             if (\
  153.                        (COMPARISON == "==" && $i == ARGUMENT) \
  154.                     || (COMPARISON == "!=" && $i != ARGUMENT) \
  155.                     || (COMPARISON == "re" && $i ~  ARGUMENT) \
  156.                     || (COMPARISON == "nr" && $i !~ ARGUMENT) \
  157.             )
  158.                 field_print($i)
  159. }
  160.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement