Site icon New Generation Enterprise Linux

Master `sed` for In-Place Text Replacement

Quick Tip

Master `sed` for In-Place Text Replacement

Challenge: You need to quickly and efficiently replace text within multiple files without manually opening each one.

The Solution: Use the `sed` command with the `-i` (in-place) option for direct modification of files.

sed -i 's/old_text/new_text/g' file1.txt file2.txt *.log

Why it works: The `sed -i` command allows `sed` to edit files in place. The `s/old_text/new_text/g` part is the substitution command: `s` for substitute, `old_text` is what you want to find, `new_text` is what you want to replace it with, and `g` means to replace all occurrences on a line, not just the first. You can specify multiple files or use wildcards.

Pro-Tip: To create a backup of the original files before making changes, add a suffix to the `-i` option, like `sed -i.bak ‘s/old_text/new_text/g’ *.txt`. This will create files ending in `.bak` with the original content.

Linux Tips & Tricks | © ngelinux.com | 5/1/2026

0 0 votes
Article Rating
Exit mobile version