如何在批处理文件中的字符串末尾附加动态数量的空格

Gha*_*ing 5 string-manipulation concatenation batch-file

我想将信息输出到日志文件中

01/08/2013 14:30 - Dynamic-Machine-Name    - Message starts
02/08/2013 07:12 - DynamicMachineName      - Log entry
02/08/2013 07:14 - Dynamic-PC-Name         - Information here
02/08/2013 08:01 - PC-Name                 - Execution continues
03/08/2013 09:00 - Dynamic-Name            - Message starts
03/08/2013 15:29 - Dynamic-Machine-Name    - Log information
03/08/2013 15:30 - Random-Machine-Name     - Message etc.
Run Code Online (Sandbox Code Playgroud)

但是为了在右侧对齐日志消息,我需要计算我已经完成的机器名称的长度,并从最大长度中减去它以获得一个数字空格。

我无法解决的是如何生成一个包含“x”个空格的字符串,或者如何将那些“x”个空格附加到机器名称的末尾?

dbe*_*ham 7

您甚至不必计算机器名称的长度。你只需要在你的消息之前知道你想要多少个字符。

假设您希望消息从位置 44 开始。您已经有了时间戳和机器名称字符串。时间戳为恒定宽度,但机器名称宽度不同。

创建一个变量,其中包含您的时间戳,后跟您的机器名称,后跟 43 个空格。然后取结果的一个子字符串,仅保留前 43 个字符,并附加您的消息。

@echo off
setlocal
set "spaces=                                           "
set "timestamp=01/08/2013 14:30"
set "machineName=PC-Name"
set "message=Message goes here"
set "line=%timestamp% - %machineName%%spaces%"
set "line=%line:~0,43%- %message%
echo %line%
Run Code Online (Sandbox Code Playgroud)

- 输出 -

01/08/2013 14:30 - PC-Name                 - Message goes here
Run Code Online (Sandbox Code Playgroud)

有关可变子字符串操作(以及搜索和替换)的更多信息,请在命令提示符下键入HELP SETSET /?