星期一, 十月 26, 2009

sed替换网址的解决方法

替换/时----
比如替换///成:::
可以用sed 's/\/\/\//:::/g' 即在前面加一个反斜杆
当然这样不友好
我们更喜欢
sed '_///_:::_g' 即把分隔符换了 换成其他符号如: 都可以的

替换一长串莫名字符,比如把以下内容//到:之间都替换成@
//abcd19388102738234:
//ijsh12398097324:
//pppppafasfae1231231:
可以用sed 's_//.*:_@_g'

sed对同一文件替换导致文件清空的原因分析

做文件替换的时候我们经常想仅用一个文件,直接替换内容,但是这个在sed里面是不可以的。

sed 's/old/new/g' filename >filename (WRONG)

因为在执行前遇到> 重定向符号,unix先把文件清空,于是没有内容。


sed替换同一文件,必须用一个临时文件。

sed 's/old/new/g' filename >filename_tmp

mv filename_tmp filename (CORRECT)


参考:

When you use redirection, the shell truncates the file before executing the command, and sed will see an empty file. You must redirect the output to a different file and then move or copy the new file over the old one, e.g.:

Pasted from <http://unix.ittoolbox.com/groups/technical-functional/shellscript-l/trying-to-change-a-file-with-sed-2242269>