Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Find Replace Text in Multiple Documents from Command Line

· 5 min read · Home Tech

In this article
  1. Why Use the Command Line for Bulk Find and Replace
  2. Basic sed Command for Multiple Files
  3. Using Perl for More Complex Replacements
  4. Handling Special Characters and Escaping
  5. Windows: PowerShell and findstr
  6. Common Pitfalls and How to Avoid Them
  7. Frequently Asked Questions

You can find and replace text across multiple documents from the command line using tools like sed, perl, or awk on Unix-like systems, or powershell on Windows. These tools let you script the replacement across many files at once, saving time compared to editing each file manually.

Why Use the Command Line for Bulk Find and Replace

When you need to update a phrase, variable name, or configuration value across dozens or hundreds of files, doing it by hand is error-prone and slow. Command-line tools are fast, repeatable, and can be combined with other commands to filter which files get changed. They also work well in automated scripts, so the same replacement can be run again later if needed.

Basic sed Command for Multiple Files

The most common tool on Linux and macOS is sed (stream editor). To replace text in place across several files, you use the -i flag (in-place) and provide a substitution expression. For example:

sed -i 's/oldtext/newtext/g' file1.txt file2.txt file3.txt

This replaces every occurrence of oldtext with newtext in each listed file. The g flag means global, so all matches on a line are replaced, not just the first. If you have many files, you can use shell wildcards:

sed -i 's/oldtext/newtext/g' *.txt

This processes all .txt files in the current directory. To include files in subdirectories, you can combine find with sed:

find . -name '*.txt' -exec sed -i 's/oldtext/newtext/g' {} +

Using Perl for More Complex Replacements

Perl is another powerful option, especially when you need regular expressions that are more advanced than what sed supports. The syntax is similar:

perl -pi -e 's/oldtext/newtext/g' file1.txt file2.txt

The -p flag makes Perl loop over lines and print them, -i edits in place, and -e specifies the expression. Perl also allows you to use variables in the replacement, which can be handy for dynamic changes. For instance, to increment a number in a file:

perl -pi -e 's/version=(\d+)/"version=".($1+1)/ge' config.txt

The e flag at the end evaluates the replacement as Perl code, so you can compute the new value.

Handling Special Characters and Escaping

When your search or replacement text contains characters that have special meaning in regular expressions (like ., *, /, or backslashes), you need to escape them. In sed, the delimiter is usually /, so if your text contains a slash, you can use a different delimiter, such as |:

sed -i 's|http://old.com|http://new.com|g' *.html

For literal dots, escape them with a backslash: \. in the pattern. Alternatively, you can use Perl with the \Q and \E escapes to treat the text literally:

perl -pi -e 's/\Qold.text\E/new.text/g' file.txt

This prevents regex interpretation, which is useful when you are not sure what characters the text contains.

Windows: PowerShell and findstr

On Windows, PowerShell provides a cmdlet called Get-Content and Set-Content that can be combined to replace text across files. A simple loop:

Get-ChildItem *.txt | ForEach-Object { (Get-Content $_.FullName) -replace 'oldtext', 'newtext' | Set-Content $_.FullName }

This reads each file, performs the replacement, and writes the result back. The -replace operator uses regex, so escaping rules apply. For a more straightforward literal replace, you can use the .Replace() method:

(Get-Content $_.FullName) -replace 'old\.text', 'new.text'

PowerShell also has findstr for searching, but it does not do replacement; you need the PowerShell approach or a third-party tool like sed for Windows (available through WSL or standalone binaries).

Common Pitfalls and How to Avoid Them

One frequent mistake is forgetting the g flag, which only replaces the first occurrence on each line. Another is accidentally modifying files you did not intend to change, especially when using wildcards. Always test your command on a small set of files first, or use the p flag in sed to print changes without saving:

sed 's/old/new/gp' file.txt

This shows what would change without modifying the file. You can also create a backup automatically with sed -i.bak to keep a copy of the original file before changes. For large directories, be careful with recursive commands—they can change files in unexpected places if your pattern is too broad.

Frequently Asked Questions

How do I replace text in files with different extensions?

Use a wildcard that matches multiple extensions, like *.*, but be cautious—this may include binary files that could get corrupted. A safer approach is to list the extensions explicitly in the find command: find . -name '*.txt' -o -name '*.md' -exec sed -i ...

Can I replace text in files without changing the original file?

Yes, you can output the result to a new file instead of using -i. For example, sed 's/old/new/g' input.txt > output.txt. This leaves the original untouched and creates a modified copy.

How do I replace text across multiple files on macOS?

macOS includes sed and perl, but the -i flag requires an argument. Use sed -i '' 's/old/new/g' file.txt (with an empty string) to avoid creating a backup file. Alternatively, use perl -pi -e which works the same as on Linux.

What if my replacement text contains special characters like backslashes?

In sed, backslashes and ampersands have special meaning in the replacement part. Escape them with backslashes: s/old/\&new/g for an ampersand. In Perl, you can use \Q and \E to treat the replacement literally, or escape each special character.

Is there a way to preview changes before applying them?

Yes, run the substitution without the -i flag and pipe the output to less or head. This shows the modified content without writing to the file. For example: sed 's/old/new/g' file.txt | less

Can I use regular expressions to replace text that spans multiple lines?

By default, sed and perl operate line by line. To match across lines, you need to use Perl with the -0 flag to treat the whole file as a single string: perl -0pi -e 's/old\nnew/new\nold/g' file.txt. This is more advanced and requires careful regex design.