1

I have multiple files named dev.rc in a very huge folder structure. These files are containing environment variables, like:

...
FOO=bar
...

I want to replace bar string along all the project with the string baz

I tried to pipe some bash commands like: find and sed but I cannot save the content of the replaced string in the original file.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
G. I. Joe
  • 1,585
  • 17
  • 21

3 Answers3

0

Use globstar to traverse through the files:

#!/bin/bash

shopt -s globstar
for file in **/dev.rc; do
  sed -i "s/=bar/=baz/" "$file"
done
codeforester
  • 39,467
  • 16
  • 112
  • 140
0

Ive written a simple PHP script to do it for you. Save it as a .php file and use it in apache localhost or run as php Remember to edit the last line of the code with your info

<?php
/*
THIS IS COMMENT SECTION TO HELP YOU
$filecount = How much files you have to replace
$location = Location of your file ; Example "usr/bk/file.txt"
$string = The string you want to replace
$newstring = The new string you want to put
*/


function replace($filecount,$location,$string,$newstring){
     for($i = 0; $i>= $filecount; $i++)
     $file = file_get_contents($location);
     file_put_contents($file,str_replace($string,$newstring,$file));
     }
}

/*
Remember to replace the variables of the function using "","",""
Below is an example calling the function, replace with your own:
*/

replace(10,"/usr/locationhere.zip","foo","bar","baz");
Gongas
  • 61
  • 9
-1

You can use a for loop to look for all the files that match the filename and then execute a simple sed command and save the content, having an automatic string replacement, as follows:

for f in `find . -name dev.rc`; do      
  sed -i '' 's/bar/baz/g' $f
done

Or you can also use exec:

find . -name 'dev.rc' -type f -exec sed -i '' 's/bar/baz/g' {} +
codeforester
  • 39,467
  • 16
  • 112
  • 140
G. I. Joe
  • 1,585
  • 17
  • 21
  • You should quote `'{}'` in your `find` example (and indent it another space so it formats correctly) – David C. Rankin Jul 20 '18 at 21:04
  • 2
    Looping through `find` output this way is not robust - it will break if the file path contains whitespaces. – codeforester Jul 20 '18 at 21:05
  • @DavidC.Rankin I've found that you don't have to quote `{}` in a `find -exec`, have you ever run into problems with it? – Benjamin W. Jul 20 '18 at 21:05
  • Well, no, not in bash, but I'm not sure that holds for all shells. By quoting, you insure no word-splitting on the filename even if it includes spaces. – David C. Rankin Jul 20 '18 at 21:09
  • 1
    @DavidC.Rankin Apparently non-POSIX shells such as fish can run into trouble with unquoted `{}`: https://superuser.com/questions/995617/difference-between-and-in-find-command – Benjamin W. Jul 20 '18 at 21:41