Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/awk -f
- # Copyright © 2021 Neo Galaxy
- #
- # Redistribution and use in source and binary forms, with or without
- # modification, are permitted provided that the following conditions are met:
- #
- # * Redistributions of source code must retain the above copyright notice, this
- # list of conditions and the following disclaimer.
- # * Redistributions in binary form must reproduce the above copyright notice,
- # this list of conditions and the following disclaimer in the documentation
- # and/or other materials provided with the distribution.
- # * Neither the name of the nor the names of its contributors may be used to
- # endorse or promote products derived from this software without specific
- # prior written permission.
- #
- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- # POSSIBILITY OF SUCH DAMAGE.
- BEGIN {
- RS=""
- FS="\n"
- # Muestra el mensaje de ayuda
- if (ARGC == 1)
- help(1)
- if (ARGV[1] == "help")
- help(0)
- # Revisa si hay suficiente argumentos.
- if (ARGC < 4)
- die("Se necesitan al menos tres argumentos")
- # Asigna los argumentos de la línea de comandos.
- FIELD = ARGV[1]
- COMPARISON = ARGV[2]
- ARGUMENT = ARGV[3]
- if (FIELD == "")
- die("FIELD está vacío")
- else if (COMPARISON == "")
- die("COMPARISON está vacío")
- else if (COMPARISON !~ /^([gl][te]|eq|ne|[!=]=|re|nr)$/)
- die("COMPARISON contiene un argumento inválido")
- else if (ARGUMENT !~ /^[[:digit:]]+$/ && COMPARISON ~ /^([gl][te]|[en]q)$/)
- die("ARGUMENT debe ser un número cuando COMPARISON es gt, ge, lt, " \
- "le, eq o nq")
- # Borra los argumentos del script para que AWK no los procese como archivos.
- ARGV[1] = ""
- ARGV[2] = ""
- ARGV[3] = ""
- # Una variable para comprobar si ya se ha imprimido.
- prev = 0
- }
- ###
- # Imprime un mensaje de error y luego cierra con código 1.
- #
- # Args:
- # message: mensaje de error a imprimir.
- ###
- function die(message) {
- printf("ERROR: %s.\n", message) > "/dev/stderr"
- exit 1
- }
- ###
- # Imprime el mensaje de ayuda.
- #
- # Args:
- # code: código de salida después de imprimir el mensaje de ayuda.
- ###
- function help(code) {
- printf \
- "Uso: field_search.awk [help] FIELD OPERATION ARGUMENT [FILE]...\n" \
- "\n" \
- "Inspecciona archivos en formato desc de Pacman e imprime los \n" \
- "resultados encontrados.\n" \
- "\n" \
- "Argumentos posicionales:\n" \
- " FIELD nombre del campo que se inspeccionará.\n" \
- " COMPARISON tipo de comparación que se realizará:\n" \
- " gt: la cantidad de campos es mayor que ARGUMENT.\n" \
- " ge: la cantidad de campos es mayor o igual que ARGUMENT.\n" \
- " lt: la cantidad de campos es menor que ARGUMENT.\n" \
- " le: la cantidad de campos es menor o igual que ARGUMENT.\n" \
- " eq: la cantidad de campos es igual a ARGUMENT.\n" \
- " ne: la cantidad de campos no es igual a ARGUMENT.\n" \
- " ==: el campo es idéntico a ARGUMENT.\n" \
- " !=: el campo es distinto a ARGUMENT.\n" \
- " re: el campo coincide con la expresión regular.\n" \
- " nr: el campo no coincide con la expresión regular.\n" \
- " ARGUMENT argumento que se pasará a la operación. No puede \n" \
- " estar vacío si OPERATION es gt o ge.\n" \
- " FILE Archivos que serán procesados.\n" \
- "\n" \
- "Argumentos opcionales:\n" \
- " help Muestra este mensaje de ayuda.\n" \
- "\n" \
- "Ejemplos:\n" \
- " field_search.awk %%DEPENDS%% gt 3 glib2-2.64.3-2/desc\n" \
- " field_search.awk %%PACKAGER%% re '<.+>' */desc\n"
- exit code
- }
- function field_print(f) {
- # Imprime el nombre del archivo si no ha sido impreso antes.
- if (printed == 0) {
- # Imprime una línea nueva antes del nombre del archivo si ya se
- # ha imprimido anteriormente.
- if (prev == 1)
- print ""
- else
- prev = 1
- printf "%s:\n", FILENAME
- printed = 1
- }
- print f
- }
- $1 == FIELD {
- # Se usa para comprobar si ya se imprimió el nombre del archivo.
- printed = 0
- num = NF - 1
- if (\
- (COMPARISON == "gt" && num > ARGUMENT) \
- || (COMPARISON == "ge" && num >= ARGUMENT) \
- || (COMPARISON == "lt" && num < ARGUMENT) \
- || (COMPARISON == "le" && num <= ARGUMENT) \
- || (COMPARISON == "eq" && num == ARGUMENT) \
- || (COMPARISON == "nq" && num != ARGUMENT) \
- )
- for (i = 2; i <= NF; i++)
- field_print($i)
- else
- # Itera sobre cada campo y comprueba si alguno de sus valores cumple con
- # los parámetros dados por el usuario.
- for (i = 2; i <= NF; i++)
- if (\
- (COMPARISON == "==" && $i == ARGUMENT) \
- || (COMPARISON == "!=" && $i != ARGUMENT) \
- || (COMPARISON == "re" && $i ~ ARGUMENT) \
- || (COMPARISON == "nr" && $i !~ ARGUMENT) \
- )
- field_print($i)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement