Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Replacing Text in Files with `sed` on Linux

1 min read .
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' *.txt

Without -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:

  • s starts a substitution.
  • abc is the search pattern.
  • aab is the replacement.
  • g replaces 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' *.txt

Because in-place editing changes data immediately, a backup is often safer:

sed -i.bak 's/abc/aab/g' *.txt

This keeps the original contents in files ending with .bak.

3. Example

Before:

abc is a test
another abc here

After running the substitution:

aab is a test
another aab here

4. 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.txt

5. 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.txt

BSD 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.txt

Check 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.

Related Posts

chevron-up