search replace in multiple files useing grep xargs sed

On many occasions we need to search and replace some text across multiple files on server. We use combination of grep, sed and xargs to achieve it mostly.

We will explain commands with examples:

Search and replace URLs in PHP files

We came across a poorly coded PHP site which was using many 4 different versions for domain names:

  1. – without www and http
  2. – with www and http
  3. – without www and https
  4. – with www and https

Final destination was: (with https and www). We setup necessary redirects on nginx side to be safe but we also decided to replace variant 1 to 3 with final variant no. 4.


Search files with matching URLs

grep -lr --include=*.php "" /var/www/
grep -lr --include=*.php "" /var/www/
grep -lr --include=*.php "" /var/www/
grep -lr --include=*.php "" /var/www/

Replace files with new URL

For variant 1 to 3… Following will replace file content without backup!

grep -lr --include=*.php "" /var/www/ | xargs sed -i -e 's/http:\/\/\/\/'
grep -lr --include=*.php "" /var/www/ | xargs sed -i -e 's/http:\/\/\/\/'
grep -lr --include=*.php "" /var/www/ | xargs sed -i -e 's/https:\/\/\/\/'

Pass an extension next to -i to create backup. For example:

grep -lr --include=*.php "" /var/www/ | xargs sed -i .bak -e 's/http:\/\/\/\/'

Changing git-remote in multiple repos

We recently shifted our git repos to another server. Below commands came in handy!

Find all config files with old remote:

grep -lr --include=config "" .

Replace with new remote:

grep -lr --include=config "" . | xargs sed -i -e 's/'

You may want to search again to make sure if all files with old remotes are replaced.

Problems with xargs? Try parallel

On Ubuntu:

apt-get install moreutils

On Mac:

brew install parallel

Just replace word xargs with parallel in commands.

Discuss your project
with our experts

No obligation. Limited slots.

Contact Form Business Enquiry

"*" indicates required fields

Please attach any RFP, project specification, or document that you would like to share.
Drop files here or
Max. file size: 5 GB.
    This field is for validation purposes and should be left unchanged.