批处理中的转义变量

时间:2017-09-09 19:07:43

标签: batch-file

我有一段代码:

for /F "tokens=*" %%A in (myfile.txt) do (
    echo echo %%A ^>^>myfile.txt>>myfile.bat
)

正如你们中的一些人所看到的,这段代码读取了myfile.txt,并创建了myfile.bat,它在打开时会创建原始myfile.txt的精确副本。当myfile.txt包含特殊字符(例如>)时会出现此问题。 如何逃避%% A变量?

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

我有这样的想法:使用Certutil命令对文本文件进行编码并再次生成它,就像这个批处理脚本可以做的那样:

@echo off
set "MyTxtFile=myfile.txt"
for %%i in (%MyTxtFile%) do (
    set "MyBatchFile=%%~ni.bat"
    set "TempFile=%%~ni.B64"
    Set "NewFile=%%~ni__%%~xi"
)

@for /f %%i in ("certutil.exe") do if not exist "%%~$path:i" (
  echo CertUtil.exe not found.
  pause
  exit /b
)

Rem to encode your text file to a temporary file
Certutil -encode "%MyTxtFile%" "%TempFile%" >nul 2>&1

(
    echo @echo off 
    echo Title Generate code of "%MyTxtFile%" to "%NewFile%"
    echo CERTUTIL -f -decode "%%~f0" "%NewFile%" ^>nul 2^>^&1 
    echo Exit
)> "%MyBatchFile%"

@Copy "%MyBatchFile%" /b + "%TempFile%" /b >nul 2>&1
Del "%TempFile%" >nul 2>&1
Timeout /T 2 /NoBreak>nul & exit

<强> 修改

此代码可根据您的上一条评论test >> Hello生成您想要的内容:

@echo off 
Title Generate code of "myfile.txt" to "myfile__.txt"
CERTUTIL -f -decode "%~f0" "myfile__.txt" >nul 2>&1 
Exit
-----BEGIN CERTIFICATE-----
dGVzdCA+PiBIZWxsbw0KDQo=
-----END CERTIFICATE-----

答案 1 :(得分:0)

以下评论代码段可以提供帮助(请参阅Variable Edit/Replace):

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion

rem silently create empty output files - just for testing
>NUL COPY /Y NUL myfile46134196.bat
>NUL COPY /Y NUL myfile46134196ou.txt

for /F "tokens=*" %%A in (myfile46134196in.txt) do (
    set "_aux=%%A"
    rem replace every `Greater Than` symbol with a properly escaped one
    echo echo !_aux:^>=^^^>! ^>^>myfile46134196ou.txt>>myfile46134196.bat
    rem             ^>       properly escape `Greater Than` symbol - input string
    rem                  ^>                                        -output string
    rem                ^^    add a caret (Circumflex Accent) to output string
)

rem debugging outputs
echo ON
type myfile46134196.bat
@ECHO OFF
rem test: run currently created .bat file
call myfile46134196.bat
rem test:                                 and show result
echo ON
type myfile46134196in.txt
type myfile46134196ou.txt
@ECHO OFF

<强>输出

==> .\so\46134196.bat

==> type myfile46134196.bat
echo test^>^>hello >>myfile46134196ou.txt

==> type myfile46134196in.txt
test>>hello

==> type myfile46134196ou.txt
test>>hello

==>

更多资源(必读,不完整):