a magnifying glass searching through text

Com trobar fitxers a Linux: dominar les ordres Find i Grep

En aquest article aprendràs a trobar fitxers a Linux utilitzant diferents eines.

The “find” command cheatsheet

Cerca per nom de fitxer

“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

Cerca per data de modificació

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

$ find /home -mtime 0

Per exemple, busquem imatges que es van modificar fa 10 dies:

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

Cerca per tipus de fitxer

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

Cerca directoris: Per trobar tots els directoris dins d'una ruta especificada, utilitzeu l'opció -type d.

$ find /home -type d

Cerca fitxers normals: Per contra, per localitzar fitxers normals, utilitzeu l'opció -type f.

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

Cerca d'enllaços simbòlics: Per cercar enllaços simbòlics, utilitzeu l'opció -type l.

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

Cerca extensions de fitxer específiques: Limiteu la cerca especificant extensions de fitxer.

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

Combinació de criteris

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

Cerca fitxers modificats amb una extensió específica: Find files modified in the last 7 days with the extension “.log”.

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

Cerca fitxers modificats entre un interval de dates: cerqueu fitxers modificats entre l'1 de novembre de 2023 i el 5 de novembre de 2023.

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

Additional “find” Command Options

Ignorant la distinció entre majúscules i minúscules: Si voleu que la cerca no distingeixi entre majúscules i minúscules, utilitzeu l'opció -iname.

$ find /home -iname "document*"

Limitació de la profunditat de cerca: Limiteu la profunditat de cerca a un nivell específic amb l'opció -maxdepth.

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

Excloent directoris específics: Exclou determinats directoris de la cerca utilitzant -not o ! opció.

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

Cerca bàsica de contingut: Per cercar una cadena específica en un fitxer, utilitzeu la sintaxi següent

$ grep "search_string" filename

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

Cerca en diversos fitxers: Si voleu cercar entre diversos fitxers, proporcioneu un comodí o un patró de fitxer específic

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

Cerca sense distinció entre majúscules i minúscules: Feu que la vostra cerca no distingeix entre majúscules i minúscules amb l'opció -i

$ grep -i "pattern" filename

Mostra números de línia: Si voleu saber els números de línia on es troba el patró, utilitzeu l'opció -n

$ grep -n "pattern" filename

Mostra només els noms dels fitxers: Per mostrar només els noms dels fitxers que contenen el patró, utilitzeu l'opció -l

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

Cerca recursivament: Si voleu cercar un patró a tots els fitxers d'un directori i els seus subdirectoris, utilitzeu l'opció -r

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

Exclou fitxers o directoris: Exclude certain files or directories from your search with the –exclude option

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

Cerca paraules senceres: Utilitzeu l'opció -w per cercar paraules senceres, evitant coincidències parcials

$ grep -w "word" filename

Advanced “grep” Usage

Cerca coincidències invertides: Inverteix la coincidència per mostrar línies que no continguin el patró especificat mitjançant l'opció -v

$ grep -v "pattern" filename

Comptant partits: Si voleu saber quantes línies contenen el patró, utilitzeu l'opció -c:

$ grep -c "pattern" filename

Es mostra només el text coincident: Mostra només el text que coincideix amb el patró amb l'opció -o:

$ grep -o "pattern" filename

Cerca recursiva amb números de línia: Combina opcions per a una cerca completa, per exemple:

$ 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ètodes de cerca de fitxers alternatius

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:

Trobeu fitxers mitjançant l'script Python

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

Actualitzeu la base de dades de localització:

$ sudo updatedb

Cerca fitxers:

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

Trobar una ubicació executable:

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

Instal·leu fd:

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

Cerca fitxers:

$ fdfind Documents
Phone/Documents
Documents
Documents.zip

Scripts personalitzats i àlies

Finalment, podeu crear scripts d'intèrpret d'ordres personalitzats o àlies per agilitzar el vostre procés de cerca de fitxers. Per exemple:

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

# Usage
$ findtxt

Els scripts i els àlies personalitzats us permeten crear dreceres per a les vostres necessitats específiques de cerca de fitxers, millorant el vostre flux de treball.

Trobeu fitxers a Linux mitjançant l'script Bash

Crear i utilitzar un script bash ajuda a automatitzar les tasques repetitives de cerca de fitxers a Linux. A continuació es mostra un exemple d'un script Bash senzill que cerca fitxers segons un patró proporcionat:

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

Deseu aquest script en un fitxer, per exemple, find_files.sh, i feu-lo executable amb l'ordre següent:

$ chmod +x find_files.sh

Ara, podeu utilitzar l'script per cercar fitxers proporcionant el directori i el patró com a arguments:

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

Aquest script comprova si es proporciona el nombre correcte d'arguments i si existeix el directori especificat. A continuació, utilitza l'ordre find per cercar fitxers segons el patró donat.

Bonificació: com cercar imatges a Linux

A Linux, hi ha diverses eines i mètodes per a la cerca d'imatges, cadascun oferint característiques i capacitats úniques. Aquí hi ha algunes opcions:

“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

Cerca imatges amb una extensió 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'

Recordeu actualitzar la base de dades de localització regularment per als canvis recents:

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

Això obre un visualitzador d'imatges amb una llista de fitxers de tots els fitxers JPEG del directori especificat.

Ús de les eines de metadades d'imatge

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'

Gestors de fitxers gràfics

Els gestors de fitxers gràfics com Nautilus, Dolphin o Thunar sovint ofereixen funcionalitats de cerca. Podeu navegar al directori i utilitzar la barra de cerca.

Organitzadors d'imatges basats en etiquetes

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

Resum

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!