Skip to main content

Find and Replace Across Multiple Files Using SSH Commands

When managing a website or application with multiple files, you might need to replace a piece of text across many pages simultaneously—like updating contact information in a footer. With SSH command line access, you can efficiently find and replace across multiple files using commands like Perl or Sed. This guide will show you how to use these tools for batch text replacement.


  • Using Perl Command
  • Using the Find Command with Sed
  • Summary

Using Perl Command

The Perl command provides a simple way to replace text across multiple files:

perl -pi -w -e 's/search/replace/g;' *.php

Here’s what each option means:

  • -e : Executes the following line of code.
  • -i : Edits files in-place, so changes are saved automatically.
  • -w : Writes warnings, helping you troubleshoot issues.
  • -p : Loops through all files, applying changes to each file in sequence.

Using the Find Command with Sed

You can also use the find command with sed to search for and replace text across all files within a directory:

find ./ -type f -exec sed -i 's/search/replace/g' {} \;

Explanation:

  • find ./ : Starts in the current directory.
  • -type f : Limits the command to files only.
  • -exec : Executes the following command on each found file.
  • sed -i 's/search/replace/g' : Replaces the search text with the replacement text in each file.

Summary

Using SSH to find and replace across multiple files saves time and ensures consistency across your website or application. By leveraging commands like Perl and Sed, you can easily update repeated information, such as contact details, throughout your files in seconds.