在文件中查找和替换并覆盖文件不起作用,它会清空文件 [英] Find and replace in file and overwrite file doesn't work, it empties the file

查看:23
本文介绍了在文件中查找和替换并覆盖文件不起作用,它会清空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过命令行对 HTML 文件进行查找和替换.

I would like to run a find and replace on an HTML file through the command line.

我的命令如下所示:

sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html > index.html

当我运行它并随后查看文件时,它是空的.它删除了我文件的内容.

When I run this and look at the file afterward, it is empty. It deleted the contents of my file.

当我再次恢复文件后运行它时:

When I run this after restoring the file again:

sed -e s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

stdout是文件的内容,已经执行了查找和替换.

The stdout is the contents of the file, and the find and replace has been executed.

为什么会这样?

推荐答案

shell 看到 >index.html 在命令行中打开文件 index.html 用于写入,擦除它之前的所有内容.

When the shell sees > index.html in the command line it opens the file index.html for writing, wiping off all its previous contents.

要解决此问题,您需要将 -i 选项传递给 sed 以进行内联更改并在更改之前创建原始文件的备份-地点:

To fix this you need to pass the -i option to sed to make the changes inline and create a backup of the original file before it does the changes in-place:

sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

如果没有 .bak,该命令将在某些平台上失败,例如 Mac OSX.

Without the .bak the command will fail on some platforms, such as Mac OSX.

这篇关于在文件中查找和替换并覆盖文件不起作用,它会清空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆