Replacing Text in Files with `sed` on Linux
Editing the same text manually across many files is slow and error-prone. The Linux sed stream editor can search, replace, delete, and transform text from the command line.
1. Preview a Replacement
Suppose several .txt files contain abc and you want to replace every occurrence with aab:
sed 's/abc/aab/g' *.txtWithout -i, sed writes the transformed content to standard output and leaves the files unchanged. This makes it useful for previewing a replacement before editing files in place.
The expression means:
sstarts a substitution.abcis the search pattern.aabis the replacement.greplaces every match on each line instead of only the first.
2. Edit Files In Place
After checking the preview, GNU sed can update the files directly:
sed -i 's/abc/aab/g' *.txtBecause in-place editing changes data immediately, a backup is often safer:
sed -i.bak 's/abc/aab/g' *.txtThis keeps the original contents in files ending with .bak.
3. Example
Before:
abc is a test
another abc hereAfter running the substitution:
aab is a test
another aab here4. Use a Different Delimiter for Paths
If the text contains many / characters, another delimiter is easier to read:
sed 's#/old/path#/new/path#g' config.txt5. Platform Differences
The exact syntax for -i differs between sed implementations. GNU sed, commonly found on Linux, accepts:
sed -i 's/old/new/g' file.txtBSD sed, used by default on macOS, typically requires an explicit backup suffix argument, even if it is empty:
sed -i '' 's/old/new/g' file.txtCheck sed --version or the local manual page when writing portable scripts.
Conclusion
sed is a fast way to perform repeatable text transformations from the shell. Preview the output first, use backups for important data, and only then apply in-place edits.