a magnifying glass searching through text

Como encontrar arquivos no Linux: dominando os comandos Find e Grep

Neste artigo você aprenderá como localizar arquivos no Linux usando diferentes ferramentas.

The “find” command cheatsheet

Pesquisando por nome de arquivo

“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

Pesquisando pela data de modificação

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

$ find /home -mtime 0

Por exemplo, vamos encontrar fotos que foram modificadas há 10 dias:

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

Pesquisando por tipo de arquivo

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

Pesquisar diretórios: Para encontrar todos os diretórios em um caminho especificado, use a opção -type d.

$ find /home -type d

Pesquisar arquivos regulares: Por outro lado, para localizar arquivos regulares, use a opção -type f.

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

Pesquise links simbólicos: Para procurar links simbólicos, utilize a opção -type l.

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

Pesquise extensões de arquivo específicas: Restrinja sua pesquisa especificando extensões de arquivo.

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

Combinando Critérios

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

Procure arquivos modificados com uma extensão específica: Find files modified in the last 7 days with the extension “.log”.

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

Pesquisar arquivos modificados entre um intervalo de datas: localize arquivos modificados entre 1º de novembro de 2023 e 5 de novembro de 2023.

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

Additional “find” Command Options

Ignorando a sensibilidade a maiúsculas e minúsculas: Se você deseja que a pesquisa não diferencie maiúsculas de minúsculas, use a opção -iname.

$ find /home -iname "document*"

Limitando a profundidade da pesquisa: Limite a profundidade da pesquisa a um nível específico com a opção -maxprofundidade.

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

Excluindo diretórios específicos: Exclua determinados diretórios da sua pesquisa usando -not ou ! opção.

$ 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:

Pesquisa de conteúdo básico: Para procurar uma string específica em um arquivo, use a seguinte sintaxe

$ grep "search_string" filename

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

Pesquise em vários arquivos: Se você quiser pesquisar vários arquivos, forneça um curinga ou um padrão de arquivo específico

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

Pesquisa sem distinção entre maiúsculas e minúsculas: Torne sua pesquisa sem distinção entre maiúsculas e minúsculas com a opção -i

$ grep -i "pattern" filename

Exibir números de linha: Se você quiser saber os números das linhas onde o padrão é encontrado, use a opção -n

$ grep -n "pattern" filename

Exibir apenas nomes de arquivos: Para mostrar apenas os nomes dos arquivos que contêm o padrão, use a opção -l

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

Pesquisar recursivamente: Se você deseja procurar um padrão em todos os arquivos de um diretório e seus subdiretórios, use a opção -r

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

Excluir arquivos ou diretórios: Exclude certain files or directories from your search with the –exclude option

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

Pesquisar palavras inteiras: Use a opção -w para pesquisar palavras inteiras, evitando correspondências parciais

$ grep -w "word" filename

Advanced “grep” Usage

Pesquisar correspondências invertidas: Inverta a correspondência para exibir linhas que não contenham o padrão especificado usando a opção -v

$ grep -v "pattern" filename

Contando partidas: Se você quiser saber quantas linhas contém o padrão, use a opção -c:

$ grep -c "pattern" filename

Exibindo apenas texto correspondente: mostre apenas o texto que corresponde ao padrão com a opção -o:

$ grep -o "pattern" filename

Pesquisa recursiva com números de linha: Combine opções para uma pesquisa abrangente, por exemplo:

$ 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 pesquisa de arquivos

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:

Encontre arquivos usando script Python

Sometimes, a custom Python script can provide more flexibility in file searching. Here’s a simple example using Python’s os e 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.

Atualize o banco de dados de localização:

$ sudo updatedb

Pesquisar arquivos:

$ 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.

Encontre o local do executável:

$ 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.

Instale o fd:

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

Pesquisar arquivos:

$ fdfind Documents
Phone/Documents
Documents
Documents.zip

Scripts e alias personalizados

Por último, você pode criar scripts de shell ou aliases personalizados para agilizar seu processo de pesquisa de arquivos. Por exemplo:

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

# Usage
$ findtxt

Scripts e aliases personalizados permitem criar atalhos para suas necessidades específicas de pesquisa de arquivos, melhorando seu fluxo de trabalho.

Encontre arquivos no Linux usando script Bash

Criar e usar um script bash ajuda a automatizar tarefas repetitivas de pesquisa de arquivos no Linux. Abaixo está um exemplo de um script Bash simples que procura arquivos com base em um padrão fornecido:

#!/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

Salve este script em um arquivo, por exemplo, find_files.sh, e torne-o executável com o seguinte comando:

$ chmod +x find_files.sh

Agora, você pode usar o script para procurar arquivos fornecendo o diretório e o padrão como argumentos:

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

Este script verifica se o número correto de argumentos foi fornecido e se o diretório especificado existe. Em seguida, ele usa o comando find para procurar arquivos com base no padrão fornecido.

Bônus: como pesquisar imagens no Linux

No Linux, existem várias ferramentas e métodos para pesquisa de imagens, cada um oferecendo recursos e capacidades exclusivos. Aqui estão algumas opções:

“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

Procure imagens com uma extensão 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'

Lembre-se de atualizar o banco de dados de localização regularmente para alterações recentes:

$ 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")

Isso abre um visualizador de imagens com uma lista de todos os arquivos JPEG no diretório especificado.

Usando ferramentas de metadados de imagem

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'

Gerenciadores de arquivos gráficos

Gerenciadores de arquivos gráficos como Nautilus, Dolphin ou Thunar geralmente fornecem funcionalidades de pesquisa. Você pode navegar até o diretório e usar a barra de pesquisa.

Organizadores de imagens baseados em tags

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

Resumo

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!