Twilight Universe


A Simple Unix Search & Replace

Posted in Articles by Gregory on the May 8th, 2007

For no apparent reason - I love working in the command line. It can’t do everything (no, really, it can’t) but it brings back memories of my old DOS days. The days I was still learning computers and drinking it all up like cold iced tea. The command line is so powerful and flexible, and because of that it can be frustrating.

For example - finding a simple string in a whole bunch of text files across multiple directories and then replacing that string in the text file. Tough to do simply in Windows normally, but I figured that, with the power of grep at my hands in Unix I could do a simple find and replace easily.

Not true, at least, not obviously true. The find part is easy, but the replace? It took me a lot of playing around to find out how to do it, amazingly it didn’t use grep (though it probably could). It fact it’s only one line of typing in the shell.

find . -name '*.html' |xargs perl -pi -e 's/find/replace/g'

That’s it, it’s that simple.

Simple?! I hear the Unix novices cry! “Simple!? How is that simple?”

Well ok, it’s actually three commands, separated by a pipe (the | above). The first finds all files which have the extension *.html, then it spits that out to perl via xargs (which just gives perl the data in a useful fashion). Perl then uses the search string in quotes to find and replace the given values. The ‘g’ on the end just tells it to replace if there are multiple instances of the search string in one line. Something you’d probably want to happen.

In fact this should also work with grep, and that way perl would only work on the files you needed, though you would be doing the searching twice - someone can probably come up with benchmarks as to what would be better performance wise.

Either way - this is something that illustrates exactly why the command line is so powerful, and so frustrating. Convoluted syntax, weird commands, strange - really counter intuitive - arguments…

… maybe it’s a conspiracy by software engineers to keep the general populous out of their world. I’m on to you!

5 Responses to 'A Simple Unix Search & Replace'

Subscribe to comments with RSS or TrackBack to 'A Simple Unix Search & Replace'.

  1. Prokur said,

    on October 16th, 2007 at 10:26

    what about list of files, where changes have een made? :)


  2. on February 21st, 2008 at 3:23

    credit check san jose ca…

    brazenly summit drawls….

  3. Anonymous said,

    on March 24th, 2008 at 6:13

    Felix Vicous College Fuck Fest…

    Felix Vicous College Fuck Fest…

  4. Anonymous said,

    on April 4th, 2008 at 5:12

    Women Fucking Or Women Pussy For Free…

    Women Fucking Or Women Pussy For Free…


  5. on July 20th, 2008 at 21:52

    vinnande baccarat system…

    Kirkland hooker impacts inefficiency …

Leave a Reply