【问题标题】:Using sed to replace multiple lines in multiple files使用sed替换多个文件中的多行
【发布时间】:2017-11-08 14:10:01
【问题描述】:

我有数千个 html 文件,其中有两段不同的旧 google adsense 代码需要用新代码替换。这些文件位于 linux 服务器上。

旧代码如下:

  <script type="text/javascript"><!--
google_ad_client = "pub-xxx";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
//2007-06-09: Forum archive rectangle
google_ad_channel = "1013717472xx";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_text = "000000";
google_color_url = "000000";
//-->
</script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

我需要在代码中匹配此文本 "google_ad_channel = "1013717472xx"",将整个代码替换为新代码。

新代码如下:

<script src="https://pagead2.googlesyndication.com/pub-config/r20160913/ca-pub-xxx.js"></script><script src="http://pagead2.googlesyndication.com/pub-config/r20160913/ca-pub-xxx.js"></script><script type="text/javascript"><!--
google_ad_client = "pub-xxx";
/* frm arch linkunit 200x90, created 5/30/08 */
google_ad_slot = "0112084554";
google_ad_width = 200;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

如何使用 sed 替换我服务器上的所有 html 文件?

提前谢谢你!

【问题讨论】:

  • 发布您的“新代码”。你的操作系统是什么?
  • 谢谢。添加了新代码,我的操作系统是 ubuntu
  • 您的“新代码”根本没有任何google_ad_channel ="..."。令人困惑
  • 文本“google_ad_channel ="..."" 是一个匹配项,一旦匹配,整个代码就会被替换。新代码中没有该术语。
  • 安装 xmlstarlet 工具,然后告诉我你什么时候准备好

标签: file sed replace lines


【解决方案1】:
ls |xargs sed -i 's/google_ad_channel = "1013717472xx"/google_ad_channel = "new_code"/g'

【讨论】:

  • 谢谢,Mikiya!但我需要替换跨越多行的整个 google adsense 代码,而不仅仅是搜索文本。
  • @bigbyte ,使用sed:labelN 可以处理多行
  • 你能把完整的代码放在这儿吗?我可以用 Perl 编程,但不能用 shell。非常感谢!
  • @bigbyte ,我需要更准确地描述要替换的行。你的意思是google_ad_channel 是正则表达式模式吗?但是“跨越多行的整个 google adsense 代码”是什么意思?
  • 要替换的代码是我原始帖子中给出的整个“旧代码”。由于在每个 html 文件中,都有两段 google adsense 代码,它们的频道号不同,这就是为什么我必须先按频道号搜索,然后替换一段 adsense 代码。
猜你喜欢
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多