我试图使用批处理文件从文件中设置变量(例如,file散列是变量名)。唉,我被困在这两个问题上:
&更改为&。我尝试过从不同来源提供的几种解决方案,但没有一种适合我的要求。
以下是我的当前代码:
@echo off
set grep=binaries\grep.exe
set fileindex=binaries\index.htm
set count=0
for /f "tokens=* delims=" %%a in (crc.dat) do (
set count=!count! + 1
set filehash=%%a
%grep% --ignore-case -w "!filehash!" %fileindex%>> list.dat
)还有一个crc.dat文件内部的例子:
Kabooom! Kablooey!
Kaboom & Kablooey以及在list.dat中使用当前代码的结果:
Kabooom Kablooey
Kaboom & Kablooey我在list.dat中期望的结果是:
Kabooom! Kablooey!
Kaboom & Kablooey我希望我能正确地表达我的问题,并提前感谢你!
发布于 2017-10-24 14:27:49
若要将&替换为&在input of grep中,请使用以下命令:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "grep=binaries\grep.exe"
set "fileindex=binaries\index.htm"
set "file=crc.dat"
set "list=list.dat"
rem // Initialise counter:
set /A "count=0"
> "%list%" (
for /F "usebackq delims=" %%a in ("%file%") do (
rem // Increment counter:
set /A "count+=1"
rem // Assign line string to variable:
set "lineitem=%%a"
rem // Toggle delayed expansion:
setlocal EnableDelayedExpansion
rem // Do sub-string replacement:
set "lineitem=!lineitem:&=&!"
rem // Execute `grep` command line:
"!grep!" --ignore-case -w "!lineitem!" "!fileindex!"
endlocal
)
)
rem // Return counter:
echo/%count%
endlocal若要将&替换为&在output of grep中,请使用以下命令:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "grep=binaries\grep.exe"
set "fileindex=binaries\index.htm"
set "file=crc.dat"
set "list=list.dat"
rem // Initialise counter:
set /A "count=0"
> "%list%" (
for /F "usebackq delims=" %%a in ("%file%") do (
rem // Increment counter:
set /A "count+=1"
rem // Execute `grep` command line and capture its output by `for /F`:
for /F "delims=" %%b in ('^""%grep%" --ignore-case -w "%%a" "%fileindex%"^"') do (
rem // Assign `grep` output to variable:
set "lineitem=%%b"
rem // Toggle delayed expansion:
setlocal EnableDelayedExpansion
rem // Do sub-string replacement:
set "lineitem=!lineitem:&=&!"
rem // Return modified string:
echo(!lineitem!
endlocal
)
)
)
rem // Return counter:
echo/%count%
endlocal通常,若要处理带有感叹号的字符串,必须切换延迟展开,以便正常的%-expanded变量和for变量引用(如%%a )在禁用延迟展开时展开。
发布于 2017-10-24 08:21:48
这是一个delayedExpansion-free的解决方案,可以将&替换为&。
@echo off
set grep=binaries\grep.exe
set fileindex=binaries\index.htm
set count=0
for /f "tokens=* delims=" %%a in (crc.dat) do (
set /a count+=1
%grep% --ignore-case -w "%%a" %fileindex%>>temp.dat
)
powershell -Command "(gc temp.dat) -replace '&', '&' | sc list.dat"
del /f temp.dat
pause
exit /b有些改变了:
set /a count+=1 = set /a count=%count%+1 !fileHash!指向%%a,那么我们为什么需要它?%%a会工作的。
powershell命令将&替换为&。https://stackoverflow.com/questions/46905407
复制相似问题