逃生可變我有一段代碼:在批量
for /F "tokens=*" %%A in (myfile.txt) do (
echo echo %%A ^>^>myfile.txt>>myfile.bat
)
中的一些人可以看到,該代碼讀取myfile.txt中,並創建myfile.bat,它打開時產生的精確副本原來的myfile.txt。當myfile.txt包含特殊字符(如>)時,問題就出現了。 如何轉義%% A變量?
任何幫助表示讚賞。
逃生可變我有一段代碼:在批量
for /F "tokens=*" %%A in (myfile.txt) do (
echo echo %%A ^>^>myfile.txt>>myfile.bat
)
中的一些人可以看到,該代碼讀取myfile.txt中,並創建myfile.bat,它打開時產生的精確副本原來的myfile.txt。當myfile.txt包含特殊字符(如>)時,問題就出現了。 如何轉義%% A變量?
任何幫助表示讚賞。
我有這樣的想法:用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-----
不,對於程序我需要echo ^> ^> >> myfile.txt格式 –
以下評論代碼片段可以幫助(見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
==>
更多資源(必讀的,不完全):
處理每一行需要轉義,爲什麼不將該文件附加到一個小的存根, '有效載荷'並在之後刪除自己? – LotPings
不,我不能。這只是較大程序的一小部分。 –
您將每個百分號加倍以避開它們。 'echo echo %%%% A ^> ^> myfile.txt >> myfile.bat' – Squashman