Skip to main content

Advanced text manipulation


Table of contents

  1. cut - Extract columns
  2. tr - Transform characters
  3. sed - Stream editor
  4. awk - Advanced processing
  5. Powerful combinations
  6. Practical exercises


1 - cut - Extract columns

Main options

OptionDescription
-dDelimiter
-fFields to extract
-cCharacters to extract
-bBytes to extract

Examples

# Extraire le premier champ (délimiteur :)
echo "alice:25:paris" | cut -d: -f1
# alice

# Plusieurs champs
echo "alice:25:paris" | cut -d: -f1,3
# alice:paris

# Plage de champs
echo "a:b:c:d:e" | cut -d: -f2-4
# b:c:d

# Depuis le champ N
echo "a:b:c:d:e" | cut -d: -f3-
# c:d:e

# Caractères
echo "Hello World" | cut -c1-5
# Hello

# Utilisateurs de /etc/passwd
cut -d: -f1,3 /etc/passwd

Practical cases

# Extraire les noms d'utilisateurs
cut -d: -f1 /etc/passwd

# Extraire IP d'un log
cat access.log | cut -d' ' -f1

# Extraire extension de fichiers
for f in *.txt; do
echo "$f" | cut -d. -f2
done

🔝 Back to table of contents



2 - tr - Transform characters

Syntax

tr [options] SET1 [SET2]

Transformations

# Minuscules vers majuscules
echo "hello" | tr 'a-z' 'A-Z'
# HELLO

# Majuscules vers minuscules
echo "HELLO" | tr 'A-Z' 'a-z'
# hello

# Classes de caractères
echo "Hello World" | tr '[:lower:]' '[:upper:]'
# HELLO WORLD

# Remplacer des caractères
echo "hello world" | tr ' ' '_'
# hello_world

Options

OptionDescription
-dDelete characters
-sSqueeze (compress repetitions)
-cComplement (all except)
# Supprimer les chiffres
echo "abc123def" | tr -d '0-9'
# abcdef

# Supprimer les non-chiffres
echo "abc123def" | tr -cd '0-9'
# 123

# Compresser les espaces multiples
echo "hello world" | tr -s ' '
# hello world

# Supprimer les retours chariot Windows
tr -d '\r' < windows.txt > unix.txt

Character classes

ClassDescription
[:alnum:]Alphanumeric
[:alpha:]Letters
[:digit:]Digits
[:lower:]Lowercase
[:upper:]Uppercase
[:space:]Whitespace
[:punct:]Punctuation

🔝 Back to table of contents



3 - sed - Stream editor

Basic commands

CommandDescription
s/old/new/Substitution
dDelete
pPrint
iInsert before
aAppend after

Substitution

# Remplacer première occurrence
echo "hello hello" | sed 's/hello/hi/'
# hi hello

# Remplacer toutes les occurrences
echo "hello hello" | sed 's/hello/hi/g'
# hi hi

# Insensible à la casse
echo "Hello HELLO" | sed 's/hello/hi/gi'
# hi hi

# Délimiteur alternatif
echo "/home/user" | sed 's|/home|/opt|'
# /opt/user

Addresses and ranges

# Ligne spécifique
sed '3s/old/new/' fichier.txt # Ligne 3 seulement

# Plage de lignes
sed '2,5s/old/new/' fichier.txt # Lignes 2 à 5

# Depuis une ligne jusqu'à la fin
sed '10,$s/old/new/' fichier.txt

# Lignes correspondant à un pattern
sed '/error/s/foo/bar/' fichier.txt

Deletion

# Supprimer une ligne
sed '5d' fichier.txt

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

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

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

In-place modification

# Modifier le fichier (-i)
sed -i 's/old/new/g' fichier.txt

# Avec backup
sed -i.bak 's/old/new/g' fichier.txt

Multiple commands

# Avec -e
sed -e 's/foo/bar/' -e 's/baz/qux/' fichier.txt

# Avec point-virgule
sed 's/foo/bar/; s/baz/qux/' fichier.txt

# Depuis un fichier de commandes
sed -f commandes.sed fichier.txt

🔝 Back to table of contents



4 - awk - Advanced processing

Structure

awk 'pattern { action }' fichier

Special variables

VariableDescription
$0Full line
$1, $2...Fields
NFNumber of fields
NRLine number
FSInput separator
OFSOutput separator

Basic examples

# Afficher le premier champ
awk '{print $1}' fichier.txt

# Plusieurs champs
awk '{print $1, $3}' fichier.txt

# Avec séparateur personnalisé
awk -F: '{print $1, $3}' /etc/passwd

# Numéro de ligne
awk '{print NR, $0}' fichier.txt

Patterns and conditions

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

# Condition sur un champ
awk '$3 > 100 {print $1, $3}' data.txt

# Plusieurs conditions
awk '$3 > 100 && $2 == "active" {print}' data.txt

# NR pour lignes spécifiques
awk 'NR >= 5 && NR <= 10' fichier.txt

Calculations

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

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

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

# Compter les occurrences
awk '{count[$1]++} END {for (k in count) print k, count[k]}' data.txt

BEGIN and END

awk '
BEGIN { print "=== Rapport ===" }
{ total += $3 }
END { print "Total:", total }
' data.txt

Formatting

# printf
awk '{printf "%-20s %10.2f\n", $1, $3}' data.txt

# Séparateur de sortie
awk 'BEGIN {OFS=","} {print $1, $2, $3}' data.txt

🔝 Back to table of contents



5 - Powerful combinations

Classic pipeline

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

# Taille des fichiers par extension
find . -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn

# Utilisateurs avec bash
grep "/bin/bash$" /etc/passwd | cut -d: -f1 | sort

Log analysis

# Erreurs par heure
grep ERROR app.log | cut -d' ' -f1 | cut -d: -f1 | uniq -c

# Requêtes HTTP 500
awk '$9 == 500 {print $7}' access.log | sort | uniq -c | sort -rn

# Temps de réponse moyen
awk '{sum += $NF; count++} END {print sum/count}' access.log

Data transformation

# CSV vers JSON (simplifié)
awk -F, 'NR>1 {printf "{\"name\":\"%s\",\"age\":%s}\n", $1, $2}' data.csv

# Transposer colonnes/lignes
awk '{for(i=1;i<=NF;i++) a[NR,i]=$i} END {for(j=1;j<=NF;j++) {for(i=1;i<=NR;i++) printf "%s ", a[i,j]; print ""}}' data.txt

🔝 Back to table of contents



6 - Practical exercises

Exercise 1: Extract information

# À partir de /etc/passwd, afficher:
# nom_utilisateur -> shell
# pour les utilisateurs avec /bin/bash
Solution
awk -F: '$7 == "/bin/bash" {print $1 " -> " $7}' /etc/passwd

Exercise 2: Clean up data

# Nettoyer un fichier:
# - Supprimer les lignes vides
# - Supprimer les commentaires (#)
# - Convertir en minuscules
Solution
sed '/^$/d; /^#/d' fichier.txt | tr '[:upper:]' '[:lower:]'

Quiz

Q1. How do you extract the 3rd field of a CSV file?

Answer

cut -d, -f3 fichier.csv or awk -F, '{print $3}' fichier.csv

Q2. How do you replace all spaces with underscores?

Answer

tr ' ' '_' or sed 's/ /_/g'

Q3. How do you compute the sum of a column with awk?

Answer

awk '{sum += $N} END {print sum}' fichier

🔝 Back to table of contents



Key takeaways

  • cut: column extraction (-d delimiter, -f fields)
  • tr: character-by-character transformation
  • sed: substitution and stream editing (s/old/new/g)
  • awk: column-oriented processing ($1, $2, calculations)
  • Combine with pipes for complex processing
  • sed -i to modify in place (with .bak backup)
  • awk BEGIN/END for initialization and finalization

🔝 Back to table of contents


← Previous chapter | Next chapter: Regular expressions →