I have:

  • Old Google analytics tracking code oldcode.txt
  • New Google analytics tracking code newcode.txt
  • 100+ html files *.html in one directory

Is it possible to replace former with latter in all html files?

  • 1
    Perhaps in the future it would make more sense for you to source the "Google_analytics.js" in each header so in the future you only need to adjust one file (obviously this doesn't work in all cases, and yours may be one of them). Looks like the answer below may work, albeit inefficiently.
    – nerdwaller
    Feb 12 '13 at 19:24

Suppose the oldcode.txt contains this:

I am the old code

And the newcode.txt looks like this:

I am the newwwwwwwwww

Then here is what you need to do:

for htmlFile in `ls *.html`; do
    cat $htmlFile | sed -i .orig 's/I am the old code/I am the newwwwwwwwww/g' > tmpCopy.html
  • The old and the new both contain multiple lines of text. Will this still work? Feb 12 '13 at 19:05
  • 2
    @FullDecent: You can enter "multiline mode" in sed with the N operator, e.g. like this: printf 'hi\nho\n' | sed -e 'N; s/i\nh/ell/'. This will print "hello". Make sure you do many test cases and escape your special characters correctly before running it for real. And have backups, as always. If you don't want to do it with sed, Perl or awk are two other popular text processing alternatives. But sed should work. Paste a specific example in your question (but anonymize personal details) for a more specific answer. Feb 12 '13 at 19:15
  • 3
    You can save a few steps here if you remove the cp, mv and rf codes. Instead, use sed -i.orig ..., that automatically creates a backup called filename.txt.orig and writes updates to the original. Just to elimate a few steps
    – nerdwaller
    Feb 12 '13 at 19:27
  • @nerdwaller - great point... did not know that! Have modified my answer Feb 12 '13 at 22:55
  • @SudiptaChatterjee I just stumbled on it recently, always nice to save some typing :)
    – nerdwaller
    Feb 12 '13 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.