2
2
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?
2
2
I have:
oldcode.txt
newcode.txt
*.html
in one directoryIs it possible to replace former with latter in all html files?
2
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
done
The old and the new both contain multiple lines of text. Will this still work? – William Entriken – 2013-02-12T19:05:27.400
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. – Daniel Andersson – 2013-02-12T19:15:11.500
3You 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 – 2013-02-12T19:27:36.647
@nerdwaller - great point... did not know that! Have modified my answer – Sudipta Chatterjee – 2013-02-12T22:55:44.970
@SudiptaChatterjee I just stumbled on it recently, always nice to save some typing :) – nerdwaller – 2013-02-12T23:53:48.350
1Perhaps 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 – 2013-02-12T19:24:54.730