Skip to content

Instantly share code, notes, and snippets.

@netwjx
Last active December 16, 2015 12:19
Show Gist options
  • Save netwjx/5433701 to your computer and use it in GitHub Desktop.
Save netwjx/5433701 to your computer and use it in GitHub Desktop.
sed多行内容替换
// many many codes
document.write('foo bar');
document.write('</div>');
// new code
var a = 'bar.js', stamp = +new Date() + '=';
document.write('<script id="foo" src="' + a + '?' + stamp + '"></script>');
// other code
document.write('<div> other text</div>');
// many many codes
document.write('foo bar');
document.write('</div>');
// new code
var a = 'foo.js';
document.write('<script id="foo" src="' + a + '"></script>');
// other code
document.write('<div> other text</div>');
> ./replace.sh > new-b.js
> diff -u b.js new-b.js
--- b.js	2013-04-22 17:52:11.756024531 +0800
+++ new-b.js	2013-04-22 17:58:32.828017570 +0800
@@ -2,7 +2,7 @@
 document.write('foo bar');
 document.write('</div>');
 // new code
-var a = 'foo.js';
-document.write('<script id="foo" src="' + a + '"></script>');
+var a = 'bar.js', stamp = +new Date() + '=';
+document.write('<script id="foo" src="' + a + '?' + stamp + '"></script>');
 // other code
 document.write('<div> other text</div>');
#!/usr/bin/env sh
sed -n '
/^document.write(\'<\/div>\')/ {
n
:start
/id="foo"/! {
N
b start
}
p
}
' a.js | sed '
/^document.write(\'<\/div>\')/ {
n
:start
/id="foo"/! {
N
b start
}
r /dev/stdin
d
}
' b.js
@netwjx
Copy link
Author

netwjx commented Apr 22, 2013

  • a.js提供替换的内容,内容在4 5 6行,标识是从document.write('</div>');开始,到id="foo"结束(包含结束的行)
  • b.js是待替换的文件,待替换的内容类似上面的范围
  • replace.sh是替换内容的sed脚本,替换结果输出到控制台
  • output.md调用和输出结果

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment