Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do a find/replace in several files?

what's the best way to do this? I'm no command line warrior, but I was thinking there's possibly a way of using grep and cat.

I just want to replace a string that occurs in a folder and sub-folders. what's the best way to do this? I'm running ubuntu if that matters.

like image 976
damon Avatar asked Feb 09 '09 18:02

damon


People also ask

How do I replace multiple file names in word?

Type the following command to rename the part of the file name and press Enter: ren OLD-FILE-NAME-PART*. * NEW-FILENAME-PART*. * In the command, replace "OLD-FILE-NAME-PART" and "NEW-FILENAME-PART" with the old and new parts of the filename.

How do you replace a string that occurs multiple times in multiple files inside a directory?

s/search/replace/g — this is the substitution command. The s stands for substitute (i.e. replace), the g instructs the command to replace all occurrences.


2 Answers

I'll throw in another example for folks using ag, The Silver Searcher to do find/replace operations on multiple files.

Complete example:

ag -l "search string" | xargs sed -i '' -e 's/from/to/g' 

If we break this down, what we get is:

# returns a list of files containing matching string ag -l "search string" 

Next, we have:

# consume the list of piped files and prepare to run foregoing command # for each file delimited by newline xargs 

Finally, the string replacement command:

# -i '' means edit files in place and the '' means do not create a backup # -e 's/from/to/g' specifies the command to run, in this case, # global, search and replace  sed -i '' -e 's/from/to/g' 
like image 192
doremi Avatar answered Sep 29 '22 00:09

doremi


find . -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g' 

The first part of that is a find command to find the files you want to change. You may need to modify that appropriately. The xargs command takes every file the find found and applies the sed command to it. The sed command takes every instance of from and replaces it with to. That's a standard regular expression, so modify it as you need.

If you are using svn beware. Your .svn-directories will be search and replaced as well. You have to exclude those, e.g., like this:

find . ! -regex ".*[/]\.svn[/]?.*" -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g' 

or

find . -name .svn -prune -o -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g' 
like image 22
Paul Tomblin Avatar answered Sep 29 '22 00:09

Paul Tomblin