Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

shell - 在文件中查找和替换,覆盖文件不起作用,它清空了文件(Find and replace in file and overwrite file doesn't work, it empties the file)

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

(我想通过命令行在HTML文件上运行查找和替换。)

My command looks something like this:

(我的命令如下所示:)

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

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

(stdout是文件的内容,并且查找和替换已执行。)

Why is this happening?

(为什么会这样呢?)

  ask by BBales translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(当外壳程序在命令行中看到> index.html ,它将打开文件index.html进行写入 ,从而清除之前的所有内容。)

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:

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...