如何在Batch的type命令中正确使用变量?消除末尾空格问题
Ah, I've run into this exact Batch quirk before! That trailing space sneaking into your variable name comes from how the echo|set /p syntax handles output—it unintentionally adds an extra space at the end of your filename when writing to beforetemp.txt. Let's fix this so your generated header has the correct indexhtml[] variable name instead of index html[].
Solution 1: Fix the Temporary File Generation
The core problem is your filename output line. Replace the echo|set /p command with a more reliable method that doesn't add extra whitespace:
@echo off setlocal enabledelayedexpansion set /P filename=Enter File name (w/o .html extension): if exist "..\website\!filename!.html" ( <nul set /p "dummyvar=!filename!">beforetemp.txt type before.txt beforetemp.txt before2.txt "..\website\!filename!.html" after.txt > "..\server\!filename!html.h" del beforetemp.txt // Clean up the temporary file after use ) else ( echo FILE at website\!filename!.html DOES NOT EXISTS! pause ) endlocal exit 0
Why this works:
<nul set /p "dummyvar=!filename!"writes the filename to the temp file without adding a trailing newline or space. Unlikeecho|set /p, this syntax usesnulas the input source forset /p, which avoids introducing extra whitespace.enabledelayedexpansionis enabled to handle any special characters in filenames (a safe practice even if your use case doesn't require it right now).
Solution 2: Remove the Temporary File Entirely (Cleaner Approach)
You can eliminate the temp file step altogether by chaining your output commands directly into the final header file:
@echo off setlocal enabledelayedexpansion set /P filename=Enter File name (w/o .html extension): if exist "..\website\!filename!.html" ( ( type before.txt <nul set /p "=!filename!" // Insert filename without extra whitespace type before2.txt type "..\website\!filename!.html" type after.txt ) > "..\server\!filename!html.h" ) else ( echo FILE at website\!filename!.html DOES NOT EXISTS! pause ) endlocal exit 0
This combines all your input files and the filename into a single output stream, which gets redirected straight to your final header. The <nul set /p "=!filename!" line inserts the filename directly between before.txt and before2.txt with no unwanted spaces.
Verify the Result
After applying either fix, your generated header will correctly look like this:
#include <arduino.h> const char indexhtml[] PROGMEM = R"====( <html> ... </html> )====";
内容的提问来源于stack exchange,提问作者Torge Rosendahl

