14 Feb 2009

Find and replace in multiple files

Just had to make a few changes to a website I own that means changing the same text in lots of files. Linux has lots of powerful tools to enable you to make this kind of change over lots of files over many directories very easily. The command is:

1
find . -type f | xargs sed -i 's/string1/string2/g'

This is basically two commands. Find will find a list of actual files (-type f, rather than symlinks or directories, etc) in this directory (.) - you could specify particular filenames by adding -iname “filename.ext” before the pipe (|).

Find outputs a list of relative filenames on each line. These are then piped (|) into xargs. xargs is a progam that runs the command that follows it (sed) once for each line of text that it receives, in this case from the pipe, it will run sed once for every filename it receives and place the filename at the end of the sed command.

The sed command is incredibly powerful and well worth learning how to use. sed stands for “Stream Editor” and edits a stream of text as instructed. xargs passes a filename for sed to operate on, then it makes a change inplace (-i), which means it changes the file rather than just outputting the change wherever you ask it to, and then carries out the actual command (‘s/string1/string2/g’).

‘s/string1/string2/g’ is in quotes to keep the scope clear, s is a command meaning substitute and the s command takes the form s/oldstring/newstring/ which means it finds the text oldstring (can be a regular expression) and replaces it with the newstring text. For each line it finds it carries it out as many times as it finds the oldstring because we’ve set the global option (g), without which it would just change the first instance of oldstring.

Hope someone finds that helpful!

comments powered by Disqus