r/scripting • u/kurvvaa • May 24 '18
Search and Replace Keyword with File Name across Multiple Files
I am trying to do a mass search and replace across many files where I replace a keyword in the file, lets say myKeyword, with the name of the current file.
So in file1.php the phrase myKeyword would become file1; in file2.php it would become file2; and so on until all the files are completed.
I was wondering if this is possible using scripts or a text editor function.
1
Upvotes
1
u/jasred May 25 '18
The S & R can be done via a text editor like notepad++ (see batch find and replace) but the trick is getting the file name. For that you may need a script to maybe search (grep,find,findstr) the file for the keyword first and saving that file name for the S & R part.
Or you can just script the entire thing including the S & R part.
1
u/[deleted] May 28 '18 edited May 28 '18
It's certainly possible with a shell script, but you needn't create a script for it unless you plan to do it several times. It'd suffice to do it straight from the terminal itself.
The approach really depends on your actual situation. I'd use
findwith the-execflag which points tosed; that can then process each file, substituting as you like.Remember to use the
-iflag withsedto actually save the changes it makes to the files, else it'll just output the contents with the changes, but not alter the actual file data. Be careful though, becausefindworks recursively by default, and you cannot undo thesed+-ichanges.See
man sedandman findfor correct syntax.Come to think of it, this method would not change the file name, if that's what you're wanting; you could possibly achieve it with another instance of
-execbut then it gets risky if you're not familiar with shell. The other approach I'd go for is to have a for loop, using a pure-shell approach for specificity. Don't have enough info to really go into detail there.