在文件中查找和替换

在文件中查找和替换

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

问题描述

我想通过命令行在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.

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

09-05 18:20