Sed
Chapter 21: sed - Stream Editor
Section titled “Chapter 21: sed - Stream Editor”Overview
Section titled “Overview”sed (Stream Editor) is a powerful text processing utility that performs editing operations on streams of text. For DevOps engineers, sed is essential for config file modifications, log processing, and automated deployments.
How sed Works
Section titled “How sed Works”┌────────────────────────────────────────────────────────────────┐│ sed Processing Flow │├────────────────────────────────────────────────────────────────┤│ ││ Input File sed Engine Output ││ ───────── ─────────── ────── ││ ││ line 1 ───► ┌─────────────┐ ──► line 1 ││ line 2 ───► │ Read line │ ──► (modified) ││ line 3 ───► │ Apply cmds │ ──► line 2 ││ ... ───► │ Output │ ──► (modified) ││ └─────────────┘ ──► line 3 ││ ... ││ ││ Cycle: Read → Pattern Space → Commands → Print → Repeat ││ │└────────────────────────────────────────────────────────────────┘Basic Syntax
Section titled “Basic Syntax”# Basic syntaxsed [options] 'command' input_file
# Common options-n # Suppress automatic output-e # Multiple commands-i # In-place editing-r # Extended regex-f # Read commands from fileSubstitution Command (s)
Section titled “Substitution Command (s)”Basic Substitution
Section titled “Basic Substitution”# Replace first occurrence in each linesed 's/old/new/' file.txt
# Replace all occurrences (global)sed 's/old/new/g' file.txt
# Replace on specific linesed '3s/old/new/' file.txt
# Replace in range of linessed '1,5s/old/new/' file.txtCase Insensitive Replace
Section titled “Case Insensitive Replace”# Case insensitivesed 's/old/new/gi' file.txt
# Exampleecho "Hello WORLD" | sed 's/world/Universe/gi'# Hello UniverseDelimiter Options
Section titled “Delimiter Options”# Use different delimiter (useful for paths)sed 's|/etc/nginx|/opt/nginx|g' file.conf
# Using # as delimitersed 's#http://#https://#g' file.html
# Using | as delimitersed 's|old|new|g' file.txtAddress Ranges
Section titled “Address Ranges”Line Numbers
Section titled “Line Numbers”# Specific linesed '5s/old/new/' file.txt
# Range of linessed '5,10s/old/new/' file.txt
# From line to endsed '5,$s/old/new/' file.txt
# First few linessed '1,3s/old/new/' file.txtPattern Matching
Section titled “Pattern Matching”# Lines matching patternsed '/error/s/old/new/' file.txt
# Range from pattern to patternsed '/start/,/end/s/old/new/' file.txt
# Multiple patternssed -e '/pattern1/s/a/b/' -e '/pattern2/s/c/d/' file.txtDeletion Commands
Section titled “Deletion Commands”Delete Lines
Section titled “Delete Lines”# Delete specific linesed '5d' file.txt
# Delete rangesed '5,10d' file.txt
# Delete from line to endsed '5,$d' file.txt
# Delete matching linessed '/error/d' file.txt
# Delete empty linessed '/^$/d' file.txt
# Delete lines starting with #sed '/^#/d' file.txt
# Delete lines starting with whitespace and #sed '/^[[:space:]]*#/d' file.txtInsert and Append
Section titled “Insert and Append”Insert Before/After
Section titled “Insert Before/After”# Insert before line 5sed '5i\New line content' file.txt
# Insert before first match of patternsed '/pattern/i\New line before' file.txt
# Append after line 5sed '5a\New line after' file.txt
# Append after first match of patternsed '/pattern/a\New line after' file.txtPractical Example
Section titled “Practical Example”# Add header to filesed '1i\=== Header Line ===' file.txt
# Add footer to filesed '$a\=== Footer Line ===' file.txtTransform Command (y)
Section titled “Transform Command (y)”Character Translation
Section titled “Character Translation”# Transform characters (like tr)sed 'y/abc/123/' file.txt# a→1, b→2, c→3
# Convert to uppercasesed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' file.txt
# Convert to lowercase (GNU sed)sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' file.txtHolding Pattern
Section titled “Holding Pattern”Using Hold Space
Section titled “Using Hold Space”# h - Copy pattern to hold# H - Append pattern to hold# g - Copy hold to pattern# G - Append hold to pattern# x - Exchange pattern and hold
# Reverse linessed '1!G;h;$!d' file.txt
# Extract first and last linesed -n '1p;$p' file.txtMultiple Commands
Section titled “Multiple Commands”Using -e
Section titled “Using -e”# Multiple editssed -e 's/old1/new1/' -e 's/old2/new2/' file.txt
# Chain of operationssed -e '1i\Header' -e '/error/d' -e 's/warn/INFO/g' file.txtUsing semicolon
Section titled “Using semicolon”# Multiple commands on same linesed 's/a/b/;s/c/d/;s/e/f/' file.txt
# With addressessed '1,5s/old/new/;10d' file.txtRegular Expressions in sed
Section titled “Regular Expressions in sed”Basic vs Extended
Section titled “Basic vs Extended”# Basic regex (default)sed 's/[0-9]*/NUM/g' file.txt
# Extended regex (-r flag)sed -r 's/[0-9]+/NUM/g' file.txt
# Using | for alternation (requires -r)sed -r 's/(error|warn|info)/LEVEL/g' file.txtPattern Examples
Section titled “Pattern Examples”# Match IP addresssed -E 's/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/IP_ADDR/g' file.txt
# Match emailsed -E 's/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/EMAIL/g' file.txt
# Match timestampsed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2}/YYYY-MM-DD/g' file.txtPractical DevOps Examples
Section titled “Practical DevOps Examples”1. Replace Configuration Values
Section titled “1. Replace Configuration Values”# Replace port in nginx configsed -i 's/listen 80/listen 8080/' /etc/nginx/nginx.conf
# Replace database hostsed -i 's/db_host=localhost/db_host=postgres/' .env
# Replace multiple valuessed -i -e 's/DEBUG=true/DEBUG=false/' \ -e 's/LOG_LEVEL=debug/LOG_LEVEL=info/' \ -e 's/MAX_WORKERS=4/MAX_WORKERS=8/' config.yaml2. Modify Log Files
Section titled “2. Modify Log Files”# Remove ANSI color codessed -r 's/\x1B\[[0-9;]*[JKmsu]//g' logfile
# Remove timestampssed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}//g' logfile
# Extract specific contentsed -n '/ERROR/p' application.log3. Docker and ContainerOps
Section titled “3. Docker and ContainerOps”# Remove stopped containersdocker ps -a | grep Exit | sed 's/ .*//' | xargs docker rm
# Remove dangling imagesdocker images | grep '<none>' | awk '{ print $3 }' | xargs docker rmi
# Extract container IPdocker inspect container_name | sed -n '/IPAddress/{s/.*: //;s/",//;p}'4. Process Kubernetes Logs
Section titled “4. Process Kubernetes Logs”# Extract specific fields from JSON logskubectl logs deployment/app | sed 's/{"time":"\([^"]*\)".*/\1/'
# Remove debug entrieskubectl logs app | sed '/DEBUG/d'
# Replace sensitive datakubectl logs app | sed -E 's/password=[^&]*/password=***/g'5. AWS CLI Output Processing
Section titled “5. AWS CLI Output Processing”# Parse EC2 instance IDsaws ec2 describe-instances | sed -n '/InstanceId/{s/.*": "//;s/",//;p}'
# Extract security group IDsaws ec2 describe-security-groups | sed -n '/GroupId/{s/.*": "//;s/",//;p}'
# Parse S3 ls outputaws s3 ls s3://bucket/ | sed 's/.* \([0-9-]*\) .*/\1/'6. Git Operations
Section titled “6. Git Operations”# Replace remote URLgit remote set-url origin $(git remote get-url origin | sed 's/https:\/\/github.com/git@github.com:/')
# Clean up branchesgit branch | sed 's/^* //' | grep 'feature-' | xargs git branch -d
# Update commit messagesgit filter-branch --msg-filter 'sed "s/old/new/"'7. File Cleanup
Section titled “7. File Cleanup”# Remove commentssed '/^[[:space:]]*#/d' config.txt
# Remove blank linessed '/^$/d' file.txt
# Remove Windows line endingssed -i 's/\r$//' file.txt
# Add line numberssed = file.txt | sed 'N;s/\n/\t/'8. System Administration
Section titled “8. System Administration”# Update /etc/hostsecho "192.168.1.100 server1" | sed -i '$a\' /etc/hosts
# Modify fstab (careful!)sed -i 's/ext3/ext4/' /etc/fstab
# Update sysctl valuessed -i 's/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/' /etc/sysctl.confIn-Place Editing
Section titled “In-Place Editing”Safe Editing
Section titled “Safe Editing”# Edit in place (creates backup)sed -i.bak 's/old/new/g' file.txt# Creates file.txt.bak as backup
# Edit in place (no backup)sed -i 's/old/new/g' file.txt
# Edit multiple filessed -i 's/old/new/g' file1.txt file2.txt file3.txtUsing symlink
Section titled “Using symlink”# Edit through symlink (preserves symlink)sed -i --follow-symlinks 's/old/new/g' /path/to/symlinkCommon sed Recipes
Section titled “Common sed Recipes”Text Replacement
Section titled “Text Replacement”# Replace first occurrence onlysed 's/old/new/'
# Replace last occurrencesed 's/.*old/new/'
# Replace word onlysed 's/\bold\b/new/g'
# Replace between delimiterssed '/start/,/end/s/old/new/g'Line Operations
Section titled “Line Operations”# Show specific linessed -n '5p' file.txtsed -n '5,10p' file.txtsed -n '5~2p' file.txt # Every 2nd line from 5
# Duplicate linessed 'p' file.txt
# Duplicate each linesed 'p;p' file.txt
# Print line numberssed '=' file.txtWhitespace Operations
Section titled “Whitespace Operations”# Remove leading whitespacesed 's/^[[:space:]]*//' file.txt
# Remove trailing whitespacesed 's/[[:space:]]*$//' file.txt
# Remove bothsed 's/^[[:space:]]*//;s/[[:space:]]*$//' file.txt
# Convert tabs to spacessed 's/\t/ /g' file.txt
# Compress multiple spacessed 's/[[:space:]]\+/ /g' file.txtSummary
Section titled “Summary”In this chapter, you learned:
- ✅ How sed works (pattern space, hold space)
- ✅ Basic substitution commands
- ✅ Address ranges (lines and patterns)
- ✅ Insert, append, and delete operations
- ✅ Character transformation with y command
- ✅ Regular expressions in sed
- ✅ Practical DevOps examples
- ✅ In-place editing and safety
Next Steps
Section titled “Next Steps”Continue to the next chapter to learn about awk - the powerful pattern scanning and processing language.
Previous Chapter: Regular Expressions Next Chapter: awk - Pattern Scanning