Tengo un archivo que contiene nombres de directorio:
my_list.txt
:
/tmp /var/tmp
Me gustaría verificar en Bash antes de agregar un nombre de directorio si ese nombre ya existe en el archivo.
grep -Fxq "$FILENAME" my_list.txt
El estado de salida es 0 (verdadero) si se encontró el nombre, 1 (falso) si no es así, entonces:
if grep -Fxq "$FILENAME" my_list.txt then # code if found else # code if not found fi
Aquí están las secciones relevantes de la página man para grep
:
grep [options] PATTERN [FILE...] -F, --fixed-strings Interpret PATTERN as a list of fixed strings, separated by new- lines, any of which is to be matched. -x, --line-regexp Select only those matches that exactly match the whole line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immedi- ately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option.
En cuanto a la siguiente solución:
grep -Fxq "$FILENAME" my_list.txt
En caso de que se pregunte (como yo lo hice) qué significa ” -Fxq
en inglés simple:
F
: Afecta cómo se interpreta PATTERN (cadena fija en lugar de una expresión regular) x
: Coincide con toda la línea q
: Shhhhh … impresión mínima Del archivo man:
-F, --fixed-strings Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified by POSIX.) -x, --line-regexp Select only those matches that exactly match the whole line. (-x is specified by POSIX.) -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.)
Tres métodos en mi mente:
1) Prueba breve de un nombre en una ruta (no estoy seguro de que este sea tu caso)
ls -a "path" | grep "name"
2) Prueba corta para una cadena en un archivo
grep -R "string" "filepath"
3) secuencia de comandos bash más larga usando regex:
#!/bin/bash declare file="content.txt" declare regex="\s+string\s+" declare file_content=$( cat "${file}" ) if [[ " $file_content " =~ $regex ]] # please note the space before and after the file content then echo "found" else echo "not found" fi exit
Esto debería ser más rápido si tiene que probar varias cadenas en un contenido de archivo utilizando un bucle, por ejemplo, cambiando la expresión regular en cualquier ciclo.
Manera más simple:
if grep "$filename" my_list.txt > /dev/null then ... found else ... not found fi
Consejo: envíe a /dev/null
si quiere el estado de salida del comando, pero no a las salidas.
Si entendí tu pregunta correctamente, esto debería hacer lo que necesites.
En una línea : check="/tmp/newdirectory"; [[ -n $(grep "^$check\$" my_list.txt) ]] && echo "dir already listed" || echo "$check" >> my_list.txt
check="/tmp/newdirectory"; [[ -n $(grep "^$check\$" my_list.txt) ]] && echo "dir already listed" || echo "$check" >> my_list.txt
La manera más fácil y simple sería:
isInFile=$(cat file.txt | grep -c "string") if [ $isInFile -eq 0 ]; then #string not contained in file else #string is in file at least once fi
grep -c devolverá el recuento de cuántas veces se produce la cadena en el archivo.
Si solo desea verificar la existencia de una línea, no necesita crear un archivo. P.ej,
if grep -xq "LINE_TO_BE_MATCHED" FILE_TO_LOOK_IN ; then # code for if it exists else # code for if it does not exist fi
Mi versión usando fgrep
FOUND=`fgrep -c "FOUND" $VALIDATION_FILE` if [ $FOUND -eq 0 ]; then echo "Not able to find" else echo "able to find" fi
grep -E "(string)" /path/to/file || echo "no match found"
-E opción hace que grep use expresiones regulares
Una solución sin grep, funciona para mí:
MY_LIST=$( cat /path/to/my_list.txt ) if [[ "${MY_LIST}" == *"${NEW_DIRECTORY_NAME}"* ]]; then echo "It's there!" else echo "its not there" fi
basado en: https://stackoverflow.com/a/229606/3306354
if grep -q "$Filename$" my_list.txt then echo "exist" else echo "not exist" fi