Search for string in files and replace string in these files only

Here is a tiny script that I like to use for batch editing files from the shell command line:

find . -iname ‘*.php’ | xargs grep ‘oldString’ -sl | xargs sed -i ‘s/oldString/newString/g’

It is a combined command that does the following:

  1. Find all files ending in ‘.php’ in the current folder or below and pipe the output via xargs to
  2. grep seach for ‘oldString’ within these files, generate a result list and pipe it to the stream editor
  3. sed, where ‘oldString’ will be replaced by ‘newString’

In this example only php files where ‘oldString’ occurs will be touched.

Make sure to only edit files you really want to by leaving out the third part:

find . -iname ‘*.php’ | xargs grep ‘oldString’ -sl

This will show you the list of files to be touched.

Tags: dev, linux

Leave a Comment