Skip to main content

Advanced search


Table of contents

  1. find: advanced search
  2. locate and updatedb
  3. Advanced grep and regex
  4. Introduction to awk
  5. Introduction to sed
  6. Hands-on exercises


Syntax

find [chemin] [critères] [actions]

Search by name

# Nom exact
find /home -name "document.txt"

# Pattern (insensible à la casse)
find /home -iname "*.txt"

# Regex
find /var -regex ".*\.log$"

Search by type

# Fichiers uniquement
find /var -type f

# Répertoires uniquement
find /home -type d

# Liens symboliques
find /etc -type l
TypeDescription
fFile
dDirectory
lSymbolic link
bBlock (device)
cCharacter (device)

Search by size

# Plus de 100 Mo
find / -type f -size +100M

# Moins de 1 Ko
find /tmp -type f -size -1k

# Exactement 10 Mo
find /home -type f -size 10M

# Entre 10 et 100 Mo
find / -type f -size +10M -size -100M

Search by time

# Modifiés dans les dernières 24h
find /var/log -type f -mtime -1

# Plus de 30 jours
find /tmp -type f -mtime +30

# Accédés dans les 7 derniers jours
find /home -type f -atime -7

# Modifiés dans les 60 dernières minutes
find /var/log -type f -mmin -60
OptionDescription
-mtimeModification (days)
-atimeAccess (days)
-ctimeInode change (days)
-mminModification (minutes)

Search by permissions

# Permissions exactes
find / -type f -perm 777

# Au moins ces permissions
find / -type f -perm -644

# SUID activé
find / -type f -perm -4000

# Fichiers world-writable
find / -type f -perm -o=w

Search by owner

# Par utilisateur
find /home -user john

# Par groupe
find /var -group www-data

# Sans propriétaire
find / -nouser

Actions

# Exécuter une commande
find /tmp -name "*.tmp" -exec rm {} \;

# Exécuter avec confirmation
find /var/log -name "*.log" -ok rm {} \;

# Afficher avec détails
find /home -type f -ls

# Supprimer directement
find /tmp -type f -mtime +7 -delete

# xargs pour efficacité
find /home -name "*.txt" -print0 | xargs -0 grep "pattern"

Combinations

# ET (par défaut)
find /var -type f -name "*.log" -size +10M

# OU
find /home \( -name "*.jpg" -o -name "*.png" \)

# NON
find /etc -type f ! -name "*.conf"

🔝 Back to table of contents



2 - locate and updatedb

locate uses a pre-indexed database.

# Installer
sudo apt install mlocate

# Rechercher
locate config.txt
locate -i README # Insensible à la casse
locate -c "*.log" # Compter

# Limiter les résultats
locate -l 10 passwd

updatedb - Update the index

# Mise à jour manuelle
sudo updatedb

# La mise à jour se fait automatiquement via cron
cat /etc/cron.daily/mlocate

find vs locate comparison

Aspectfindlocate
SpeedSlow (real time)Fast (database)
FreshnessAlways up to dateMay be outdated
CriteriaVery flexibleName only
UsageComplex searchesFast name searches

🔝 Back to table of contents



3 - Advanced grep and regex

Advanced grep options

# Récursif dans les dossiers
grep -r "error" /var/log/

# Avec numéro de ligne
grep -n "error" fichier.log

# Contexte (lignes avant/après)
grep -B 2 -A 2 "error" fichier.log
grep -C 3 "error" fichier.log

# Compter
grep -c "error" fichier.log

# Fichiers correspondants seulement
grep -l "error" *.log

# Inverser (lignes NE contenant PAS)
grep -v "debug" fichier.log

# Plusieurs patterns
grep -E "error|warning|critical" fichier.log

Basic regular expressions

PatternMeaning
.Any character
^Start of line
$End of line
*0 or more of the previous character
+1 or more (with -E)
?0 or 1 (with -E)
[]Character class
[^]Class negation
\Escape

Regex examples

# Lignes commençant par "Error"
grep "^Error" fichier.log

# Lignes terminant par un chiffre
grep "[0-9]$" fichier.log

# Adresses IP (simplifié)
grep -E "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log

# Emails (simplifié)
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" fichier

# Dates au format YYYY-MM-DD
grep -E "[0-9]{4}-[0-9]{2}-[0-9]{2}" fichier

# Mots de 5 lettres exactement
grep -E "\b[a-zA-Z]{5}\b" fichier

🔝 Back to table of contents



4 - Introduction to awk

What is awk?

awk is a column-oriented text processing language.

Structure

awk 'condition { action }' fichier

Column processing

# Afficher la première colonne
awk '{print $1}' fichier.txt

# Afficher plusieurs colonnes
awk '{print $1, $3}' fichier.txt

# Dernière colonne
awk '{print $NF}' fichier.txt

# Nombre de colonnes
awk '{print NF}' fichier.txt

Special variables

VariableDescription
$0The entire line
$1, $2...Columns 1, 2...
$NFThe last column
NRLine number
NFNumber of fields
FSInput separator
OFSOutput separator

Change the separator

# Fichier CSV (séparateur virgule)
awk -F',' '{print $1, $2}' fichier.csv

# Fichier /etc/passwd (séparateur :)
awk -F':' '{print $1, $3}' /etc/passwd

Conditions

# Lignes où colonne 3 > 100
awk '$3 > 100 {print}' fichier.txt

# Lignes contenant "error"
awk '/error/ {print}' fichier.log

# Lignes 10 à 20
awk 'NR >= 10 && NR <= 20' fichier.txt

Calculations

# Somme d'une colonne
awk '{sum += $3} END {print sum}' fichier.txt

# Moyenne
awk '{sum += $3; count++} END {print sum/count}' fichier.txt

# Maximum
awk 'BEGIN {max=0} $3>max {max=$3} END {print max}' fichier.txt

Practical examples

# Top 5 IPs dans access.log
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -5

# Utilisateurs avec UID > 1000
awk -F':' '$3 >= 1000 {print $1}' /etc/passwd

# Taille totale des fichiers
ls -l | awk '{total += $5} END {print total/1024/1024 " Mo"}'

🔝 Back to table of contents



5 - Introduction to sed

What is sed?

sed (Stream EDitor) modifies text line by line.

Substitution

# Remplacer première occurrence par ligne
sed 's/ancien/nouveau/' fichier.txt

# Remplacer toutes les occurrences
sed 's/ancien/nouveau/g' fichier.txt

# Insensible à la casse
sed 's/ancien/nouveau/gi' fichier.txt

# Modifier le fichier en place
sed -i 's/ancien/nouveau/g' fichier.txt

# Avec backup
sed -i.bak 's/ancien/nouveau/g' fichier.txt

Delete lines

# Supprimer une ligne spécifique
sed '5d' fichier.txt

# Supprimer les lignes 5 à 10
sed '5,10d' fichier.txt

# Supprimer les lignes contenant un pattern
sed '/pattern/d' fichier.txt

# Supprimer les lignes vides
sed '/^$/d' fichier.txt

Display lines

# Afficher uniquement les lignes 5 à 10
sed -n '5,10p' fichier.txt

# Afficher les lignes contenant un pattern
sed -n '/error/p' fichier.txt

Insert text

# Insérer avant la ligne 3
sed '3i\Nouvelle ligne' fichier.txt

# Ajouter après la ligne 3
sed '3a\Nouvelle ligne' fichier.txt

# Ajouter à la fin de chaque ligne
sed 's/$/ FIN/' fichier.txt

# Ajouter au début de chaque ligne
sed 's/^/DEBUT /' fichier.txt

Practical examples

# Remplacer dans plusieurs fichiers
sed -i 's/localhost/192.168.1.100/g' *.conf

# Supprimer les commentaires
sed '/^#/d' fichier.conf

# Supprimer les espaces en fin de ligne
sed 's/[[:space:]]*$//' fichier.txt

# Convertir dos2unix
sed -i 's/\r$//' fichier.txt

🔝 Back to table of contents



6 - Hands-on exercises

Exercise 1: find

# 1. Trouvez tous les fichiers .conf dans /etc
find /etc -name "*.conf" -type f 2>/dev/null | head -10

# 2. Trouvez les fichiers > 10Mo dans /var
sudo find /var -type f -size +10M 2>/dev/null

# 3. Trouvez les fichiers modifiés aujourd'hui
find /home -type f -mtime 0 2>/dev/null

Exercise 2: grep and regex

# 1. Créez un fichier de test
cat << 'EOF' > test_grep.txt
Error: connection failed
Warning: low memory
Info: process started
ERROR: disk full
error: timeout
EOF

# 2. Trouvez toutes les erreurs (insensible à la casse)
grep -i "error" test_grep.txt

# 3. Comptez les erreurs
grep -ci "error" test_grep.txt

# 4. Nettoyez
rm test_grep.txt

Exercise 3: awk

# Analysez /etc/passwd
# 1. Affichez nom:home de chaque utilisateur
awk -F':' '{print $1 ":" $6}' /etc/passwd

# 2. Comptez les utilisateurs avec shell /bin/bash
awk -F':' '$7 == "/bin/bash"' /etc/passwd | wc -l

Quiz

Q1. How do you find files larger than 100 MB?

Answer

find / -type f -size +100M

Q2. How do you display the 3rd column with awk?

Answer

awk '{print $3}' fichier

Q3. How do you replace "foo" with "bar" in all .txt files?

Answer

sed -i 's/foo/bar/g' *.txt

🔝 Back to table of contents



Key takeaways

  • find = real-time search, very flexible
  • locate = fast search by name (indexed database)
  • grep -E for extended regexes
  • awk = column processing ($1, $2, $NF)
  • sed = substitution (s/ancien/nouveau/g)
  • The -i option of sed modifies in place
  • Always test before using -i!

🔝 Back to table of contents


← Previous chapter | Next chapter: Review exercises →