这是我在批处理脚本中的第一次体验,我正在尝试读取文本文件内容并尝试在单个变量中设置其内容我使用.bat文件来运行脚本但脚本无效。
我想在单个变量中设置文件的所有内容
尝试了大多数例子,但失败了。
下面是我正在尝试的脚本
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "delims=" %%x in (Test.txt) do set Build=%%x
pause >nul
exit
这是我的文本文件
和
以下结果显示
答案 0 :(得分:2)
cd "C:\documents and settings\%USERNAME%\desktop"
setlocal enableDelayedExpansion
for /f "useback delims=" %%x in ("Test.txt") do set "Build=!build! %%x"
echo %build%
pause >nul
exit
请注意,您可以为变量指定的字符串的最大长度为8191个符号。
此外,一些特殊符号可能会破坏上面的脚本(%
,!
..)
答案 1 :(得分:0)
我想在单个变量中设置文件的所有内容。
批量处理的唯一方法是自己构造一个多行变量,名为!LF!
@echo off
SETLOCAL EnableDelayedExpansion
::Change this
set "file=%~f0"
if NOT EXIST "%file%" exit /b 1
::Initialize & empty variables
( set LF=^
%= 0x0D Form Feed =%
)
set "lines="
set "data="
::Count lines
FOR /F tokens^=*^ delims^=^ eol^= %%L in (
'2^>nul findstr /N "^" "%file%"'
) do set /a "lines+=1"
::Read file using SET /P
<"%file%" (
for /L %%a in (1 1 %lines%) do (
set "x=" %= Workaround for empty lines =%
set /p "x="
set "data=!data!!LF!!x!"
)
)
::Print data
echo(!data!
ENDLOCAL
pause & exit /b
FOR /F tokens^=*^ delims^=^ eol^=
通过escaping every delimiter禁用eol
。 警告:"eol="
不禁用eol
,但禁用sets the quote "
as the end-of-line character!
缺点:
\n
或\r\n
被忽略,并且始终设置为\n
)\n
优势:
答案 2 :(得分:0)
您还可以使用@dbenham的CERTUTIL
method。绝对不会<CR> <LF> ! ^
...
有关深入介绍的more tricks with certutil开关,请参见"poorly documented"。
@echo off
====SETLOCAL EnableDelayedExpansion EnableExtensions
set "B=^!"
set "C=^"
set ^"L=^
%===Line Feed===%
"
for /F %%C in ('wmic qfe list') do set "R=%%C" Carriage Return
>nul 2>&1 certutil -f -encodehex Test.txt "%temp%\hex.txt" 4
pushd "%temp%"
>expand.txt (
for /f "delims=" %%A in (hex.txt) do for %%B in (%%A) do (
set "char=%%B"
REM ! --> !B!
set "char=!char:21=21 42 21!"
REM ^ --> !C!
set "char=!char:5e=21 43 21!"
REM <CR> --> !R!
set "char=!char:0a=21 4c 21!"
REM <LF> --> !L!
set "char=!char:0d=21 52 21!"
echo(!char!
)
)
>nul 2>&1 certutil -f -decodehex expand.txt rawContent.txt
for /f delims^=^ eol^= %%A in (rawContent.txt) do set "fileContent=%%A"
del hex.txt expand.txt rawContent.txt
popd
echo(!fileContent!