windows bat 函数来编辑文件(在文件的开头添加一行)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3836259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:20:30  来源:igfitidea点击:

bat function to edit a file (add line to start of a file)

windowsbatch-file

提问by Berming

In my bat script, what do I use to open a file called open.txt and add the following line to the top

在我的 bat 脚本中,我用什么来打开一个名为 open.txt 的文件并将以下行添加到顶部

SOME TEXT TO BE ADDED

Can small edits like this be handled in a .bat script

可以在 .bat 脚本中处理这样的小编辑吗

回答by paxdiablo

Sure, with something like:

当然,有类似的东西:

copy original.txt temp.txt
echo.SOME TEXT TO BE ADDED>original.txt
type temp.txt >>original.txt
del temp.txt

The first line makes a temporary copy of the file. The second line overwrites the file with the line you want to add (note particularly the lack of spaces between the text being added and the >redirection operator - echohas a nasty habit of including such spaces).

第一行是文件的临时副本。第二行用您要添加的行覆盖文件(请特别注意添加的文本和>重定向运算符之间缺少空格-echo包含此类空格的坏习惯)。

The third line uses the append redirection operator >>to add the original file to the end of the new one, then the final line deletes the temporary file.

第三行使用追加重定向运算符>>将原始文件添加到新文件的末尾,然后最后一行删除临时文件。

回答by ghostdog74

you can do just simple echos and redirection. but if you can download sed for windows, here's how you can do it

你可以做简单的echos 和重定向。但是如果你可以下载windows 的 sed,你可以这样做

C:\test> sed -i.bak "1 i text" file

If download is impossible, you can use vbscript

如果无法下载,可以使用vbscript

strAddText= WScript.Arguments(0)
strFileName = WScript.Arguments(1)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFS.OpenTextFile(strFileName)
WScript.Echo strAddText
Do Until objFile.AtEndOfStream
    WScript.Echo objFile.ReadLine
Loop    

To use:

使用:

C:\test> cscript //nologo myscript.vbs "text to add" myfile  > newfile