Capítulo 3.6 - Búsqueda de Archivos
Objetivos de Aprendizaje
Al final de este capítulo, usted será capaz de:
- Utilizar find de manera eficiente
- Utilizar locate para búsquedas rápidas
- Buscar por contenido con grep
- Combinar herramientas de búsqueda
find - Búsqueda Potente
Sintaxis Básica
find [chemin] [critères] [actions]
Búsqueda por Nombre
# Por nombre exacto
find /home -name "fichier.txt"
# Insensible a mayúsculas/minúsculas
find /home -iname "fichier.txt"
# Patrones
find /home -name "*.txt"
find /home -name "file*"
find /home -name "*log*"
Búsqueda por Tipo
# Solo archivos
find /home -type f
# Solo directorios
find /home -type d
# Enlaces simbólicos
find /home -type l
# Tipos especiales
find /dev -type b # Block devices
find /dev -type c # Character devices
Búsqueda por Tamaño
# Más de 100MB
find /home -size +100M
# Menos de 1KB
find /home -size -1k
# Exactamente 50MB
find /home -size 50M
# Unidades: c (bytes), k, M, G
Búsqueda por Fecha
# Modificado en la última semana
find /home -mtime -7
# Modificado hace más de 30 días
find /home -mtime +30
# Modificado en la última hora
find /home -mmin -60
# Por fecha de acceso
find /home -atime -7
# Por fecha de creación
find /home -ctime -7
Búsqueda por Permisos
# Archivos ejecutables
find /home -type f -perm /111
# Archivos con permisos específicos
find /home -perm 644
# Archivos sin permisos para otros
find /home ! -perm -o=r
Búsqueda por Propietario
# Por usuario
find /home -user user1
# Por grupo
find /home -group developers
# Por UID/GID
find /home -uid 1000
find /home -gid 1000
Acciones con find
# Mostrar (por defecto)
find /home -name "*.txt"
# Ejecutar un comando
find /home -name "*.txt" -exec ls -lh {} \;
find /home -name "*.txt" -exec rm {} \;
# Eliminar directamente
find /home -name "*.tmp" -delete
# Copiar
find /home -name "*.txt" -exec cp {} /backup/ \;
# Con confirmación
find /home -name "*.txt" -ok rm {} \;
Combinaciones
# Archivos .log modificados en la última semana, más de 10MB
find /var/log -name "*.log" -mtime -7 -size +10M
# Archivos .txt que pertenecen a user1, ejecutables
find /home -name "*.txt" -user user1 -perm /111
# Directorios vacíos
find /home -type d -empty
locate - Búsqueda Rápida
Uso
# Búsqueda simple
locate fichier.txt
# Insensible a mayúsculas/minúsculas
locate -i fichier
# Limitar el número de resultados
locate -l 20 fichier
# Patrones
locate "*.txt"
locate "file*"
Actualización de la Base
# Actualizar la base de datos
sudo updatedb
# Ver las bases utilizadas
locate -S
Ventajas:
- Muy rápido
- Índice preconstruido
Desventajas:
- Requiere updatedb regular
- Puede no encontrar archivos recientes
grep - Búsqueda en el Contenido
Búsqueda de Texto
# Búsqueda simple
grep "motif" fichier.txt
# Insensible a mayúsculas/minúsculas
grep -i "motif" fichier.txt
# Mostrar números de línea
grep -n "motif" fichier.txt
# Mostrar solo los nombres de archivos
grep -l "motif" *.txt
# Búsqueda recursiva
grep -r "motif" /home/user1/
# Búsqueda inversa (líneas sin el patrón)
grep -v "motif" fichier.txt
Patrones Avanzados
# Expresiones regulares
grep "^début" fichier.txt # Comienza con
grep "fin$" fichier.txt # Termina con
grep "motif1\|motif2" fichier.txt # O
grep "[0-9]" fichier.txt # Dígitos
grep "[a-z]" fichier.txt # Letras minúsculas
# Búsqueda extendida
grep -E "motif1|motif2" fichier.txt
Opciones Útiles
# Contexto (líneas antes/después)
grep -C 3 "motif" fichier.txt # 3 líneas antes/después
grep -B 2 "motif" fichier.txt # 2 líneas antes
grep -A 2 "motif" fichier.txt # 2 líneas después
# Contar las ocurrencias
grep -c "motif" fichier.txt
# Colores
grep --color=auto "motif" fichier.txt
Combinación de Herramientas
find + grep
# Buscar en todos los archivos .txt
find /home -name "*.txt" -exec grep -l "motif" {} \;
# Buscar y mostrar con contexto
find /home -name "*.log" -exec grep -Hn "ERROR" {} \;
find + xargs
# Más eficiente que -exec
find /home -name "*.txt" | xargs grep "motif"
find /home -name "*.txt" -print0 | xargs -0 grep "motif"
Pipeline Complejo
# Encontrar archivos .log, buscar ERROR, contar
find /var/log -name "*.log" -exec grep "ERROR" {} \; | wc -l
# Encontrar archivos modificados recientemente, buscar patrón
find /home -mtime -1 -type f -exec grep -l "motif" {} \;
which y whereis
which
Encuentra la ubicación de un comando:
which ls
which python
which git
whereis
Encuentra binario, fuente y man:
whereis ls
whereis python
# Muestra: binario, fuente, man pages
Resumen
En este capítulo, usted ha aprendido:
find: Búsqueda potente por nombre, tipo, tamaño, fecha, permisos
locate: Búsqueda rápida con índice
grep: Búsqueda en el contenido de los archivos
which/whereis: Encontrar comandos
Combinaciones: find + grep, find + xargs para eficiencia
Próximos Pasos
Capítulo 3.7: Enlaces Simbólicos y Duros
Capítulo 3.8: Tipos de Sistemas de Archivos
Capítulo creado el: Diciembre 2024