做文件替换的时候我们经常想仅用一个文件,直接替换内容,但是这个在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>
1 条评论:
可以使用 -i 选项,直接对原文件处理
发表评论