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!