我有一个简单的问题。
是否可以将变量从.bat文件传递到.txt文件?我在网上找到的就是在文件末尾附加变量或覆盖整个.txt文件。 是否可以在.txt文件中保留{0},{1}变量捕获器或类似内容,因此我可以使用.bat命令在运行它时将变量发送到.txt文件以获取这些特定位置?
只是一般的想知道,如果可能或正确的方法是覆盖.txt文件并且我自己只在这些地方包含我的变量。
答案 0 :(得分:1)
您可以在批处理文件中“滥用”变量扩展过程以获得类似的内容
template.txt
The element !data1! refers to !data2!
Also, the element !data3! points to !data4!
You will need to escape exclamations
Escaped exclamation : ^!
Non escaped exclamation : !
;
; !data4!
;
process.cmd
@echo off
setlocal enableextensions disabledelayedexpansion
rem Define the set of data that will be replaced
set "data1=TEST"
set "data2=This is the data in || TEST ||"
set "data3=Another test!"
set "data4=< data inside [Another test!]>"
rem Read template (uses findstr /n to retrieve empty lines)
for /f "delims=" %%a in ('findstr /n "^" "template.txt"') do (
rem Retrieve line
set "line=%%a"
rem To retrieve the data in line var we need delayed expansion
setlocal enabledelayedexpansion
rem Output template line after removing initial numbers
rem On empty lines the for command "fails". This is detected and
rem handled by echoing an empty line
(for /f delims^=^ eol^= %%b in ("!line:*:=!") do echo(%%b)||echo(
rem Cancel delayed expansion
endlocal
)
控制台输出
W:\45820941>process
The element TEST refers to This is the data in || TEST ||
Also, the element Another test! points to < data inside [Another test!]>
You will need to escape exclamations
Escaped exclamation : !
Non escaped exclamation :
;
; < data inside [Another test!]>
;
W:\45820941>