Home > bash > replace a string recursively in multiple files

replace a string recursively in multiple files

Problem
In a folder I have lots of files, and the folder also has subdirectories with further files. I want to replace a string in all of them. I want to modify the files in place.

For instance, you want to update a bunch of Python scripts from version 2 to version 3, thus you want to modify the first lines from “#!/usr/bin/env python2” to “#!/usr/bin/env python3“.

Solution
I found the solution here:

grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @

WARNING! Since it modifies the files in place, be very careful! First run just the beginning of the command above:

grep -rli 'old-word' *

Refine it if necessary. If it finds exactly what you need, then proceed.

Categories: bash Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: