Suggestion to Up Your Bash Skills: Multiple Find/Replace with sed Command

Listen to this Post

Using `sed` for multiple replacements can significantly streamline your text manipulation tasks in Linux. Here’s a deep dive into its practical applications, with verified commands and examples.

Basic `sed` Syntax for Find/Replace

The core syntax for substitution in `sed` is:

sed 's/old_text/new_text/g' filename

– `s` stands for substitution.
– `g` replaces all occurrences (global).

Removing Brackets in One Command

Instead of chaining multiple `sed` commands, combine them using -e:

echo "[This String Was in Brackets]" | sed -e 's/[//g' -e 's/]//g'

Output:

This String Was in Brackets

Advanced `sed` Use Cases

  1. Replace Multiple Patterns in a File

sed -i -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt

– `-i` edits the file in-place.

2. Delete Lines Containing a Specific Word

sed '/error/d' logfile.txt
  1. Insert Text Before or After a Match
    sed '/pattern/i\Insert this before' file.txt Insert before
    sed '/pattern/a\Insert this after' file.txt Insert after
    

4. Use Regex for Complex Replacements

echo "123-456-7890" | sed -E 's/([0-9]{3})-([0-9]{3})-([0-9]{4})/(\1) \2-\3/g'

Output:

(123) 456-7890

You Should Know:
– Escape Special Characters: Use `\` for [ ] { } ( ) . + ? ^ $ \ |.
– Case-Insensitive Replacement: Add `I` flag (sed 's/word/WORD/gI').
– Print Only Modified Lines: Use `-n` with `p` (sed -n 's/foo/bar/p').

What Undercode Say
Mastering `sed` enhances automation, log parsing, and bulk text edits. Combine it with `awk` and `grep` for powerful shell scripting. Always test replacements with `echo` before modifying files.

Expected Output:
[/bash]

This String Was in Brackets

(123) 456-7890

For further reading:
– GNU `sed` Manual: https://www.gnu.org/software/sed/manual/sed.html
– Advanced Regex Guide: https://www.regular-expressions.info/

References:

Reported By: Activity 7314987459207991296 – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image