You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Batch的type命令中正确使用变量?消除末尾空格问题

Fix Trailing Space Issue When Generating ESP8266 PROGMEM Headers with Batch Script

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. Unlike echo|set /p, this syntax uses nul as the input source for set /p, which avoids introducing extra whitespace.
  • enabledelayedexpansion is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:07:40