🔥 What is sed?
sed stands for Stream Editor — it's a powerful Unix tool to search, find and replace, insert, and delete text in files or streams non-interactively.
🧠 sed Syntax
sed [OPTIONS] 'COMMAND' file
Breakdown:
COMMAND: Script-like instructions, e.g., 's/old/new/g'
file: Input text file or stream (can also be piped)
📘 SECTION 1: BASIC COMMANDS
1️⃣ Print a file
sed '' filename
2️⃣ Delete lines
3️⃣ Find and replace
4️⃣ Case insensitive replace
📘 SECTION 2: INTERMEDIATE USAGE
5️⃣ In-place edit with -i
6️⃣ Insert / Append text
7️⃣ Replace on a specific line
8️⃣ Replace using regex patterns
📘 SECTION 3: ADVANCED USE CASES
9️⃣ Replace text between two markers
🔟 Remove comments from config files
11️⃣ Change multiple patterns
⚙️ Real-Time Use Cases (DevOps/Data)
✅ Clean log files
✅ Mask sensitive info
✅ Change URL in CI/CD pipeline YAML
✅ Parse output from commands
❓ FAANG-Level Interview Questions with Answers
Q1: How would you replace the 3rd occurrence of a word in a line using sed?
Q2: Delete all blank lines and lines starting with #
Q3: Use sed to replace only within a function in a file (e.g., between { and })
sed '/function_name {/,/}/s/foo/bar/' file.sh
Q4: What does sed -n '5p' file.txt do?
A: It prints only the 5th line (-n suppresses automatic output).
Q5: How can you extract everything before a delimiter (:)?
sed 's/:.*//' file.txt
🧪 Practice Exercises
Mask all email addresses in a file
Remove HTML tags from a file
Replace tabs with commas
Swap two columns (use sed + awk)
📌 Tips
📺 Recommended YouTube Channels
Linux Leech – deep dive into sed and shell scripting
The Net Ninja – Bash scripting series
Chris Titus Tech – Linux command mastery
TechTFQ – Unix interview questions
Here's a focused and clear tutorial on how to find lines using sed and then insert or append lines before or after the match, including FAANG-level examples.
🔍 PART 1: FIND and INSERT / APPEND in sed
🔸 Syntax Overview
🧪 PRACTICAL EXAMPLES
✅ 1. Insert line before a match
sed '/server_name/i\# Inserted line before server_name' nginx.conf
📌 Before:
📌 After:
✅ 2. Append line after a match
sed '/server_name/a\# Appended line after server_name' nginx.conf
📌 After:
✅ 3. Insert a line before every line matching a keyword (e.g., ERROR)
✅ 4. Append a blank line after each } (useful in code formatting)
✅ 5. Insert multiple lines before match
(Each new line ends with \, escape newline)
✅ 6. Append content from a file after a pattern
Appends file_to_append.txt after every line that matches pattern.