[原创]FreeBSD下用sed实现批量替换_VMware, Unix及操作系统讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  VMware, Unix及操作系统讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3201 | 回复: 0   主题: [原创]FreeBSD下用sed实现批量替换        下一篇 
wulcan
版主
等级:中校
经验:1795
发帖:124
精华:0
注册:2014-3-19
状态:离线
发送短消息息给wulcan 加好友    发送短消息息给wulcan 发消息
发表于: IP:您无权察看 2014-11-26 11:29:07 | [全部帖] [楼主帖] 楼主

在命令行下批量替换某个字符,能搜索到的基本上全是Linux下的gunsed命令,在这个版本下,sed有个-i参数,表示--in-replce,表示现场编辑,意思是直接保留编辑完的结果,而不是显示到屏幕上。

但是在FreeBSD下,-i会提示错误,比如:

hu@mm:~/test % uname -a
FreeBSD mm.test.com 9.1-STABLE FreeBSD 9.1-STABLE #3 r248486: Tue Mar 19 11:39:02 CST 2013 root@mm.test.com:/usr/obj/usr/src/sys/JWM amd64
hu@mm:~/test % cat 1.txt
abcdefg
abcdefg
abcdefghijklmn
abcdefghijklmn
hu@mm:~/test %


直接运行则会提示错误:

hu@mm:~/test % sed -i "s/abc/DDD/g" 1.txt
sed: 1: "1.txt": invalid command code .


man sed,查看i和I的参数;

-I extension
Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.
……
-i extension
Edit files in-place similarly to -I, but treat each file independently from other files. In particular, line numbers in each file start at 1, the ``$'' address matches the last line of the current file, and address ranges are limited to the current file. (See Sed Addresses.) The net result is as though each file were edited by a separate sed instance.


会发现-i跟Linux下的不一样,后面必须跟一个extension参数,并且指出:是现场编辑,并且使用指定的extension来备份原文件。那么这个extension是什么意思呢?

原来,sed考虑到数据的安全,在保存结果前,先把原来的数据备份一份,放在原来的目录下,为了使文件不重复,在后面加上一个新的扩展名,比如.bak,这样就可以区别开来了。

所以,为备份指定一个.bak扩展名,就会在该目录下产生一个.bak文件:

hu@mm:~/test % sed -i .bak "s/abc/DDD/g" 1.txt
hu@mm:~/test % ll 1.*
-rw-r--r-- 1 hu wheel 46 Oct 27 15:38 1.txt
-rw-r--r-- 1 hu wheel 46 Oct 27 15:06 1.txt.bak


查看内容:

hu@mm:~/test % cat 1.txt
DDDdefg
DDDdefg
DDDdefghijklmn
DDDdefghijklmn


看bak文件的内容:

hu@mm:~/test % cat 1.txt.bak
abcdefg
abcdefg
abcdefghijklmn
abcdefghijklmn
hu@mm:~/test %


这只是针对某一个文件,批量替换呢?那就结合find得了:

find ./ -name "*.txt" -exec sed -i .bak "s/abc/III/g" {} \;


如果确定没问题了,可以删除.bak文件:

find ./ -name “*.bak” –exec rm {} \;


注意:按照sed 的手册,extension可以长度为零,注意这不是啥也没有,什么也没有的话,sed就会把后面的替换内容作为extension了,长度为零正常情况下就是空的双引号,用空的双引号作为参数,则不存备份。但是sed后加了一句,小心在某种情况下会导致空间用尽——具体情况还不明确,有待验证。

该贴由hui.chen转至本版2014-11-27 18:24:24




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论