Batch file 要搜索的批处理文件?并将其替换为txt文件中的%

Batch file 要搜索的批处理文件?并将其替换为txt文件中的%,batch-file,vbscript,Batch File,Vbscript,我要搜索批处理文件?符号,并将其替换为txt文件中的%symbol 我看到很多搜索和替换代码,它是不是不替换?含% 如果任何一个有代码并且它在vbs上工作,请发布它 例如: @echo off setlocal set "search=?" set "replace=%" set "textfile=test.txt" set "newfile=newte

我要搜索批处理文件?符号,并将其替换为txt文件中的%symbol

我看到很多搜索和替换代码,它是不是不替换?含%

如果任何一个有代码并且它在vbs上工作,请发布它

例如:

 @echo off     
 setlocal
 set "search=?"                              
 set "replace=%"                              
 set "textfile=test.txt"
 set "newfile=newtest.txt"

 (for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
 set "line=%%i"
 setlocal enabledelayedexpansion
 set "line=!line:%search%=%replace%!"
 echo(!line!
 endlocal
 ))>"%newfile%"
 type "%newfile%" > nul

这可以在powershell的帮助下轻松实现,只需从命令控制台使用一行命令。请参见下面的示例。如果计划在批处理文件中使用它,请将%替换为%%

C:\Scripts>type input.txt
Sometext ? here
here is another ? text
?? test file..
sample??

C:\Scripts>powershell -command (get-content input.txt ^| %{ $_ -replace \"\?\",\"%\"})
Sometext % here
here is another % text
%% test file..
sample%%

干杯,G

此批处理解决方案优于所讨论的批处理脚本,因为它不会向新文件添加行号

@echo off
setlocal EnableDelayedExpansion
set "search=?"
set "replace=%%"
set "textfile=test.txt"
set "newfile=newtest.txt"
if exist "%newfile%" del "%newfile%"
for /F "usebackq delims=" %%L in ("%textfile%") do (
   set "Line=%%L"
   set "Line=!Line:%search%=%replace%!"
   if not "!Line: =!"=="" echo !Line!>>"%newfile%"
)
endlocal
注意


将行复制到
newtest.txt
时,
替换为
%
,将删除空行和
test.txt中仅有空格的行。只有水平制表符的一行将获得写入新文件的
echo
状态。因此,我建议使用文本编辑器而不是批处理文件进行替换,尽管我认为可以改进代码,将空行和仅带空格的行复制到新文件。

@Mofi-只需将此作为答案发布即可。尽管我不确定OP是否希望在新文件中添加行号,谢谢Mofi,但这是可行的!!必须对其进行修改以使其在批处理文件中工作-需要将
%%
加倍为
%%
@echo off
setlocal EnableDelayedExpansion
set "search=?"
set "replace=%%"
set "textfile=test.txt"
set "newfile=newtest.txt"
if exist "%newfile%" del "%newfile%"
for /F "usebackq delims=" %%L in ("%textfile%") do (
   set "Line=%%L"
   set "Line=!Line:%search%=%replace%!"
   if not "!Line: =!"=="" echo !Line!>>"%newfile%"
)
endlocal