Batch Find and Replace with the Linux Command Line

Two simple, rather elegant, solutions:

perl -pi -w -e ‘s/wrong/right/g;’ *.html
Replaces all instances of ‘wrong’ with ‘right’ in html files within the current working directory.

grep -rl “wrong” /home/jerrywaller  | xargs sed -i ‘s|wrong|right|g’
Recursively replaces ‘wrong’ with ‘right’ within the designated directory.

Just make sure you use plain single and double quotation marks, and not the smart quotes that may show up in the formatting above.  Hat tip to the author and commenters here and here.  Now both options are in one convenient location.  ;)

Advertisements

9 thoughts on “Batch Find and Replace with the Linux Command Line

  1. Ben

    Thank you for this simple and FUNCTIONAL solution. There are about a million suggestions on how to do this and most of them either don’t work or they’re not recursive. This did the trick beautifully.

  2. Anonymous

    Is there any reason it would fail when trying to convert special characters (ù) to their html equivalent (ù)? I’m getting success if I try a test string (boobs -> noboobs), but I really need to to fix the special characters some users have dumped on a website and it fails. It doesn’t seem to be a problem of the punctuation in the html sting, I get the same fail doing (ù -> bb).

    Thanks in advance for your help. Love the idea if I can get it to work.

  3. John

    Is there any reason it would fail when trying to convert special characters (ù) to their html equivalent (ù)? I’m getting success if I try a test string (boobs -> noboobs), but I really need to to fix the special characters some users have dumped on a website and it fails. It doesn’t seem to be a problem of the punctuation in the html sting, I get the same fail doing (ù -> bb).

    Thanks in advance for your help. Love the idea if I can get it to work.

  4. John

    Turns out the mime-encoding of the files I’m trying to work with are all over the place. Might have something to do with my troubles. I’ll poke away and see how it goes. Looks promising, thanks.

  5. Hi John,
    That sounds along the lines of what I was thinking. I suspect that the right combination of utf-8 unicode values would help, somewhat along the lines of this Q&A over at stackoverflow.

    BTW, love your sense of humor wrt “boobs noboobs”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s