免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 2887 | 回复: 11
打印 上一主题 下一主题

批处理查找替换大量html文件办法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-07-22 17:12 |只看该作者 |倒序浏览
任务很简单,把6000多个htm文件加上 adsesne 和样式表。最后的命令行如下:

find . -name "*.html" -exec sed -i "s/<body>/<link rel=\"stylesheet\" type=\"text\/css\" href=\"style.css\" \/>\n<body>\n<div id=\"ad1\" style=\"float:left;\">\n<script type=\"text\/javascript\"><\!--\ngoogle_ad_client = \"pub-3332674173523723\";\n\/* 160x600, created 3\/4\/08 *\/\ngoogle_ad_slot = \"8263104448\";\ngoogle_ad_width = 160;\ngoogle_ad_height = 600;\n\/\/-->\n<\/script>\n<script type=\"text\/javascript\"\nsrc=\"http:\/\/pagead2.googlesyndication.com\/pagead\/show_ads.js\">\n<\/script>\n<\/div>\n/g" {} \;

解释如下:

一开始尝试 rpl 命令,很简单,但不能处理 ! 号。在 shell 中 ! 号用别的用处,需要 \!,但很遗憾 rpl 输出的也是 \!。只好用 sed 搞定。


sed "s/abc/def/g" 123.txt

把 123.txt 文件中的 abc 换成 def,输出到终端。s 表示搜索,/g表示全局。

sed -i 123.txt

表示就地修改。123.txt

sed -iback 123.txt

表示修改后的文件另存为 123.txtback

注意:

sed 的正则比较严格: " \ / ! 都需要分别用 \" \/ \\ \! 转义。

\n 表示换行

find .

在当前目录中找

find . -name "*.html"

找那些后缀为 html 的文件。

find . -name "*.html" -exec ABC {} \;

对找到的每个文件执行 ABC 操作。

by guoshuang 2008-03-14

http://wiki.guoshuang.com/%E6%89 ... 6%E5%8A%9E%E6%B3%95

论坛徽章:
1
荣誉会员
日期:2011-11-23 16:44:17
2 [报告]
发表于 2008-07-22 17:17 |只看该作者
都看晕了~~~~~~~~~~~~~

论坛徽章:
0
3 [报告]
发表于 2008-07-22 17:19 |只看该作者
转贴。

论坛徽章:
0
4 [报告]
发表于 2008-07-22 18:23 |只看该作者
sed -ir 's#str#rep#g'

用这个模式应该能简单很多

论坛徽章:
0
5 [报告]
发表于 2008-07-22 19:29 |只看该作者
s后面的单个字符自动作为分隔符,可以是,、1、a。
info sed:
The syntax of the `s' (as in substitute) command is
`s/REGEXP/REPLACEMENT/FLAGS'.  The `/' characters may be uniformly
replaced by any other single character within any given `s' command.
The `/' character (or whatever other character is used in its stead)
can appear in the REGEXP or REPLACEMENT only if it is preceded by a `\'
character.

论坛徽章:
0
6 [报告]
发表于 2008-07-22 19:47 |只看该作者
看到眼花了...

论坛徽章:
0
7 [报告]
发表于 2008-07-22 22:06 |只看该作者
眼花缭乱

论坛徽章:
0
8 [报告]
发表于 2008-07-23 01:17 |只看该作者
弱弱的说下:
sed -ie  '    '     这样里面的" " 应该就不需要转移了。

还有个疑问: lz为什么不写成 shell文件加注释? 命令行太长了。

论坛徽章:
0
9 [报告]
发表于 2008-07-23 01:20 |只看该作者
抱歉, 没看清。  原来楼主就用了一次替换,注释似乎不用很多。 ——!

论坛徽章:
0
10 [报告]
发表于 2008-07-23 03:29 |只看该作者
不好看...不好读
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP