Unix find and replace in directory

20091202894

I’m not well versed in command line tools. I have a few basic tasks that I do regularly (zip, svn, move, text edit) that I’m real comfortable with but beyond that I depend on Google. A lot. When I’m working out some new command I often get a bit nervous. Is this going to blow something up that I then won’t know how to fix without more extensive Googling? When it works I feel like a ninja. Some moments of complete satisfaction.

Until a month later when I need to do it again and can’t remember how I did it.

Find and replace

Besides the default purple and pink CSS syntax highlighting of Dreamweaver, my other favorite feature is the find and replace functionality. Despite its slightly off regex syntax, it works miracles when needing to replace text across an entire site – if it’s local or FTP access. Depending on it has left me a bit lost in when dealing with replacing in multiple files via more direct means.

Google turned up a lot of long winded scripts or perl commands. I needed something simple. Eventually I found this post. While it was helpful, the comments actually gave me the best solution for my case:


grep -rl 'something' * | xargs sed -i 's/something/something new/g'

Obviously I’m not an expert on this, but here goes. The idea is to find all the files with the string in it and then replace that string with the new string in each of them.

grep is used with the r and l flags. This does it recursively and outputs a list of just the file name of each file containing the string (something). The * means look in every file in the current working directory. This could be replaced with a path to a different directory.

The grep output (a list of file names) gets piped to xargs which handles passing each argument in the list (each filename) to sed.

sed does the actual text replacement on each file passed in to it. The i flag edits the file in place rather than saving as a new file. This apparently isn’t available on all instances, so check the man page to be sure it is. sed has a number of commands, subsitution being the most popular. 's/something/something new/g' says do substitution of “something” with “something new”. The forward slash is a common delimiter but a different character could be used if needed due to a forward slash being part of the search or replacement string. For example, ‘s|something|something new|g’ would also work. The g at the end makes the replacement global. Otherwise only the first instance of the string in the file would be replaced. Note that if not using the global flag you still need the final forward slash (or other chosen delimiter).

Next time, less Google and more replace.


Skateboards and bikes are better at nights

Skateboards and bikes are better at nights. 0 comments.


Search WayTooCrowded
The Header Should Always Point Home