我现在有以下bat文件工作(允许一个文本添加到文件每行的末尾) - 请参阅: bat file: Use of if, for and a variable all together
@echo off
setLocal EnableDelayedExpansion
IF EXIST "%FileToModify1%" (
for /f "tokens=* delims= " %%a in (%FileToModify1%) do (
echo %%a Note: certain conditions apply >> "%SaveFile1%"
)
)
但是,我想将每一行保存到变量(包括新行符号),然后将变量回显到最后的文件。由于文件中有多行,因此保存到每行的文件效率非常低。
我试过谷歌搜索,但答案不符合我的情况......
基本上我需要连接和保存到变量的语法(在C#中累计像“+ =”),并且还需要使用新行......
答案 0 :(得分:2)
实际上,您不需要将所有内容都放入变量中,只需将重定向放在另一个位置即可。 试试这个:
@echo off
setlocal EnableDelayedExpansion
if exist "%FileToModify1%" (
for /F "usebackq delims=" %%a in ("%FileToModify1%") do (
echo %%a Note: certain conditions apply
)
) > "%SaveFile1%"
endlocal
请注意for /F
会忽略原始文件中的空行,因此它们不会传输到新文件。 ;
也会忽略以for /F
开头的行(除非您更改eol
选项 - 请参阅for /?
)。
我修改了for /F
选项:
delims
,因此每行按原样输出("tokens=* delims= "
,如果存在,则从每行中删除前导空格); usebackq
允许在""
中包含文件规范,如果它包含空格则很有用; 如果您仍想将文件内容存储到变量中,可以执行以下操作:
@echo off
setlocal EnableDelayedExpansion
rem the two empty lines after the following command are mandatory:
set LF=^
if exist "%FileToModify1%" (
set "FileContent="
for /F "usebackq delims=" %%a in ("%FileToModify1%") do (
set "FileContent=!FileContent!%%a Note: certain conditions apply!LF!"
)
(echo !FileContent!) > "%SaveFile1%"
)
endlocal
文件内容存储在变量FileContent
中,包括附录Note: certain conditions apply
。 LF
包含换行符号。
注意:强>
变量的长度非常有限(据我所知,自Windows XP起为8191个字节,之前为2047个字节)!
[参考文献:
Store file output into variable(最后一段代码片段);
Explain how dos-batch newline variable hack works]
或者,您可以将文件内容存储在数组中,如下所示:
@echo off
setlocal EnableDelayedExpansion
if exist "%FileToModify1%" (
set /A cnt=0
for /F "usebackq delims=" %%a in ("%FileToModify1%") do (
set /A cnt+=1
set "Line[!cnt!]=%%a Note: certain conditions apply"
)
(for /L %%i in (1,1,!cnt!) do (
echo !Line[%%i]!
)) > "%SaveFile1%"
)
endlocal
文件的每一行都存储在数组Line[1]
,Line[2]
,Line[3]
等中,包括附录Note: certain conditions apply
。 cnt
包含总行数,即数组大小。
注意:强>
实际上这不是真正的数组数据类型,因为它不存在于批处理中,它是具有数组样式命名的标量变量的集合(Line[1]
,Line[2]
,...);因此可以将其称为伪阵列。
[参考文献:
Store file output into variable(第一个代码片段);
How to create an array from txt file within a batch file?]
答案 1 :(得分:1)
您可以一次性写出输出文件:
(
for /l %%i in (0,1,10) do (
echo line %%i
)
)>outfile.txt
(比分别追加每一行快得多)