这个方便的perl one liner在名为test.txt的文件中用“bar”替换所有出现的“foo”:
perl -pi -e 's/foo/bar/g' test.txt
这非常有用,但……
如果test.txt所在的文件系统磁盘空间不足,则test.txt将被截断为零字节文件.
是否有一种简单的,无竞争条件的方法来避免这种截断发生?
我希望test.txt文件保持不变,如果文件系统空间不足,则返回错误的命令.
理想情况下,应该可以从shell脚本中轻松使用该解决方案,而无需安装其他软件(超出“标准”UNIX工具,如sed和perl).
谢谢!
解决方法
perldoc perlrun
开始:
-i[extension]
specifies that files processed by the “
<>
” construct are to be edited in-place.
It does this by renaming the input file,opening the output file by the original
name,and selecting that output file as the default forprint()
statements. The
extension,if supplied,is used to modify the name of the old file to make a
backup copy,following these rules:If no extension is supplied,no backup is made and the current file is
overwritten.[…]
转述:
>备份文件名由-i-switch的值决定,如果给出的话.
>原始文件重命名为新文件名,并为脚本打开.在大多数文件系统上重命名都是原子的.
>打开具有原始文件名称的文件以进行写入.该文件将以长度为零开始,但与原始文件(现在具有不同的名称)不同.
>脚本完成后,如果未提供显式备份扩展,则删除备份文件.然后原始文件丢失.
如果系统用完了驱动器空间,那么新文件就会受到威胁,而不是永远不会复制或移动的原始文件(至少在具有类似inode概念的文件系统上).