Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
share|improve this answer
The old and the new both contain multiple lines of text. Will this still work? – Full Decent Feb 12 '13 at 19:05
@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. – Daniel Andersson Feb 12 '13 at 19:15
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 – Sudipta Chatterjee 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .