a magnifying glass searching through text

Cómo buscar archivos en Linux: dominar los comandos Find y Grep

En este artículo aprenderá cómo buscar archivos en Linux usando diferentes herramientas.

The “find” command cheatsheet

Buscando por nombre de archivo

“Find” is one of the most popular tools to search files in Linux. When you know the file name you can search for it using command below. Replace “/home” with a folder to search through and “filename.txt” with the file name.

$ find /home -name filename.txt

To search the current folder for a file replace “/home” with a dot (.) symbol:

$ find . -name Documents.zip
./Documents.zip

When you do not know the exact file name use the regular expression to look for a match. The asterisk (*) symbol matches any character set after the “Documents” keyword.

$ find /home -name "Documents*"
/home/eugene/Documents.zip
/home/eugene/Documents
/home/eugene/Phone/Documents

Buscando por fecha de modificación

To search for files that were modified today add “-mtime” key to the find command:

$ find /home -mtime 0

Por ejemplo, busquemos imágenes que se modificaron hace 10 días:

$ find Pictures/ -mtime 10
Pictures/Screenshots/Screenshot from 2023-11-03 10-29-49.png

Búsqueda por tipo de archivo

The “find” command in Linux allows you to search for files based on their type. Here are some examples:

Buscar directorios: Para buscar todos los directorios dentro de una ruta especificada, utilice la opción -type d.

$ find /home -type d

Buscar archivos normales: Por el contrario, para localizar archivos normales, utilice la opción -type f.

$ find /home -type f -name "*.txt"

Búsqueda de enlaces simbólicos: Para buscar enlaces simbólicos, utilice la opción -type l.

$ find /home -type l -name "linkname"

Busque extensiones de archivos específicas: Limite su búsqueda especificando extensiones de archivo.

$ find /home -type f -name "*.jpg"

Combinando criterios

You can combine multiple criteria to make your searches more precise. Here’s an example:

Buscar archivos modificados con una extensión específica: Find files modified in the last 7 days with the extension “.log”.

$ find /var/logs -type f -name "*.log" -mtime -7

Buscar archivos modificados entre un rango de fechas: Localice archivos modificados entre el 1 de noviembre de 2023 y el 5 de noviembre de 2023.

$ find /home -newermt 2023-11-01 ! -newermt 2023-11-06

Additional “find” Command Options

Ignorando la distinción entre mayúsculas y minúsculas: Si desea que la búsqueda no distinga entre mayúsculas y minúsculas, utilice la opción -iname.

$ find /home -iname "document*"

Limitar la profundidad de búsqueda: Limite la profundidad de búsqueda a un nivel específico con la opción -max Depth.

$ find /home -maxdepth 2 -name "*.txt"

Excluyendo directorios específicos: Excluya ciertos directorios de su búsqueda usando -not o ! opción.

$ find /home -type f -name "*.txt" -not -path "/home/user/exclude/*"

Remember, mastering the “find” command can significantly enhance your ability to navigate and manage files in a Linux environment. Experiment with different options to tailor your searches according to specific criteria.

Search by file content using “grep” command

When it comes to finding specific content within files, the “grep” command becomes your go-to tool. It allows you to search for patterns or text strings within one or multiple files. Here’s a quick cheatsheet to get you started:

Búsqueda de contenido básico: Para buscar una cadena específica en un archivo, utilice la siguiente sintaxis

$ grep "search_string" filename

Replace “search_string” with the text you’re looking for and “filename” with the name of the file.

Buscar en varios archivos: Si desea buscar en varios archivos, proporcione un comodín o un patrón de archivo específico

$ grep "pattern" /path/to/files/*.txt

Búsqueda que no distingue entre mayúsculas y minúsculas: Haga que su búsqueda no distinga entre mayúsculas y minúsculas con la opción -i

$ grep -i "pattern" filename

Mostrar números de línea: Si desea saber los números de línea donde se encuentra el patrón, use la opción -n

$ grep -n "pattern" filename

Mostrar sólo nombres de archivos: Para mostrar solo los nombres de los archivos que contienen el patrón, use la opción -l

$ grep -l "pattern" /path/to/files/*.txt

Buscar recursivamente: Si desea buscar un patrón en todos los archivos dentro de un directorio y sus subdirectorios, use la opción -r

$ grep -r "pattern" /path/to/directory

Excluir archivos o directorios: Exclude certain files or directories from your search with the –exclude option

$ grep "pattern" --exclude=*.log /path/to/files/*

Buscar palabras completas: Utilice la opción -w para buscar palabras completas, evitando coincidencias parciales

$ grep -w "word" filename

Advanced “grep” Usage

Buscar coincidencias invertidas: Invierta la coincidencia para mostrar líneas que no contengan el patrón especificado usando la opción -v

$ grep -v "pattern" filename

Contando coincidencias: Si quieres saber cuántas líneas contiene el patrón, usa la opción -c:

$ grep -c "pattern" filename

Mostrar solo texto coincidente: muestra solo el texto que coincide con el patrón con la opción -o:

$ grep -o "pattern" filename

Búsqueda recursiva con números de línea: Combine opciones para una búsqueda exhaustiva, por ejemplo:

$ grep -r -n "pattern" /path/to/directory

Mastering the “grep” command allows you to swiftly locate specific content within files, making it an indispensable tool for efficient file exploration in a Linux environment. Experiment with different options to tailor your searches and uncover the information you need.

Métodos alternativos de búsqueda de archivos

In addition to the powerful “find” and “grep” commands, there are alternative methods for searching files in a Linux environment. Let’s explore a few:

Buscar archivos usando el script Python

Sometimes, a custom Python script can provide more flexibility in file searching. Here’s a simple example using Python’s os y fnmatch modules:

import os
from fnmatch import fnmatch

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if fnmatch(file, pattern):
                print(os.path.join(root, file))

# Usage
find_files('/path/to/search', '*.txt')

This script walks through the directory and its subdirectories, matching files based on the specified pattern. Customize the find_files function to suit your specific search criteria.

The “locate” Command

The “localizar” command is another efficient way to find files on a Linux system. It uses a pre-built index, making searches faster compared to the “find” command. However, keep in mind that the index needs regular updates to include recent changes.

Actualice la base de datos de localización:

$ sudo updatedb

Buscar archivos:

$ locate filename.txt

Using the “which” Command

If you’re looking for the location of an executable in your system’s PATH, the “which” command can help.

Buscar ubicación ejecutable:

$ which executable_name

Using “fd” – A Fast and User-friendly Alternative to “find”

The “fd” command is a fast and user-friendly alternative to “find.” It comes with a simplified syntax and colorized output.

Instalar fd:

$ sudo apt-get install fd-find # For Ubuntu/Debian
$ sudo dnf install fd # For Fedora

Buscar archivos:

$ fdfind Documents
Phone/Documents
Documents
Documents.zip

Scripts y alias personalizados

Por último, puede crear scripts de shell o alias personalizados para agilizar el proceso de búsqueda de archivos. Por ejemplo:

# Custom Alias
alias findtxt='find /path/to/search -name "*.txt"'

# Usage
$ findtxt

Los scripts y alias personalizados le permiten crear accesos directos para sus necesidades específicas de búsqueda de archivos, mejorando su flujo de trabajo.

Buscar archivos en Linux usando el script Bash

Crear y utilizar un script bash ayuda a automatizar tareas repetitivas de búsqueda de archivos en Linux. A continuación se muestra un ejemplo de un script Bash simple que busca archivos según un patrón proporcionado:

#!/bin/bash

# Bash script to find files based on a pattern

if [ $# -ne 2 ]; then
echo "Usage: $0 <directory> <pattern>"
exit 1
fi

directory=$1
pattern=$2

# Check if the directory exists
if [ ! -d "$directory" ]; then
echo "Error: Directory $directory not found."
exit 1
fi

# Use find command to search for files
find "$directory" -name "$pattern" -print

Guarde este script en un archivo, por ejemplo, find_files.sh, y hágalo ejecutable con el siguiente comando:

$ chmod +x find_files.sh

Ahora, puedes usar el script para buscar archivos proporcionando el directorio y el patrón como argumentos:

$ ./find_files.sh /path/to/search "*.txt"

Este script comprueba si se proporciona la cantidad correcta de argumentos y si el directorio especificado existe. Luego utiliza el comando de búsqueda para buscar archivos según el patrón dado.

Bonificación: cómo buscar imágenes en Linux

En Linux, existen varias herramientas y métodos para la búsqueda de imágenes, cada una de las cuales ofrece características y capacidades únicas. Aquí hay algunas opciones:

“find” Command with File Type Filtering:

The standard “find” command can be used to locate image files based on their file types. For example, to find all JPEG files in a directory and its subdirectories:

$ find /path/to/images -type f -name "*.jpg"

The “fdfind” Command:

The “fdfind” command, a fast and user-friendly alternative to “find,” can also be used to search for image files. Install it if you haven’t already:

$ sudo apt-get install fd-find # For Ubuntu/Debian
$ sudo dnf install fd # For Fedora

Busque imágenes con una extensión específica:

$ fdfind -e jpg

The “locate” Command

The “locate” command can be used for quick searches, especially if an updated database is maintained:

$ locate '*.jpg'

Recuerde actualizar la base de datos de localización periódicamente para ver los cambios recientes:

$ sudo updatedb

“grep” Command for Specific Image Names:

If you have a specific naming convention for your image files, you can use the “grep” command to search for them:

$ grep -r 'pattern' /path/to/images

Replace ‘pattern’ with a part of the image file name.

“file” Command

The “file” command can identify file types, helping you filter out image files:

$ file /path/to/images/*

Look for lines that include “image” to identify image files.

“feh” Image Viewer with Filelist

If you have a list of image files and want to view them, the “feh” image viewer allows you to create a filelist:

$ feh -f $(find /path/to/images -type f -name "*.jpg")

Esto abre un visor de imágenes con una lista de archivos de todos los archivos JPEG en el directorio especificado.

Uso de herramientas de metadatos de imágenes

If your images have metadata, you can use tools like “exiftool” to search based on image properties:

$ exiftool -filename -r /path/to/images | grep 'search_term'

Administradores de archivos gráficos

Los administradores de archivos gráficos como Nautilus, Dolphin o Thunar suelen ofrecer funciones de búsqueda. Puede navegar hasta el directorio y utilizar la barra de búsqueda.

Organizadores de imágenes basados ​​en etiquetas

Tools like “digiKam” or “Shotwell” offer image organization based on tags. Tag your images and use these tools to search based on tags.

Resumen

In conclusion, mastering file search on Linux involves understanding and combining various commands, tools, and scripting techniques. Whether you’re a command-line enthusiast or prefer graphical interfaces, this guide equips you with the knowledge to navigate and search for files seamlessly in a Linux environment. Happy file hunting!