【问题标题】:format output from BAT file to console [closed]格式从 BAT 文件输出到控制台 [关闭]
【发布时间】:2022-01-10 06:03:34
【问题描述】:

我想要这个
echo %%~nxa !newsize! !unit! 输出,以便 newsize 从控制台上的特定列开始。问题是 %%~nxa 是可变长度的,因此添加制表符或其他字符不起作用。

有没有办法让 newsize 从特定列开始或根据 %%~nxa 的长度添加选项卡。

【问题讨论】:

  • FOR 变量分配给环境变量,并在末尾添加空格。 set "filename=%%~nxa " 然后将其子串为您想要的任何内容。 echo !filename:~0,20!
  • 是的,有办法。问题是,你为什么需要它?用于显示输出或进一步处理? %%~nxa 应该是文件名吗?另外,到目前为止,您尝试过什么?

标签: batch-file format output


【解决方案1】:

如果您想要动态列格式化功能,您可以使用这里的功能。您也可以左右对齐数据列。

@echo off
setlocal
set "filename=ReallyLongFileName.txt"
set "newsize=20,000"
set "unit=300"

call :Format "[30] [20] [10]" "%filename%" "%newsize%" "%unit%"

set "filename=Some Other Long FileName.txt"
set "newsize=200,000"
set "unit=3000"

call :Format "[30] [20] [10]" "%filename%" "%newsize%" "%unit%"

exit /b

REM FUNCTIONS BELOW
:Format Fmt [Str1] [Str2]...
setlocal disableDelayedExpansion
set "fmt=%~1"
set "line="
set "space=                                                                                                    "
setlocal enableDelayedExpansion
for %%n in (^"^

^") do for /f "tokens=1,2 delims=[" %%a in (".!fmt:]=%%~n.!") do (
  if "!!" equ "" endlocal
  set "const=%%a"
  call set "subst=%%~2%space%%%~2"
  setlocal enableDelayedExpansion
  if %%b0 geq 0 (set "subst=!subst:~0,%%b!") else set "subst=!subst:~%%b!"
  for /f delims^=^ eol^= %%c in ("!line!!const:~1!!subst!") do (
    endlocal
    set "line=%%c"
  )
  shift /2
)
setlocal enableDelayedExpansion
echo(!line!
exit /b

运行这段代码会输出

ReallyLongFileName.txt         20,000               300
Some Other Long FileName.txt   200,000              3000

如果你想右对齐最后一列,只需将 10 更改为 -10,它就会像这样输出。

ReallyLongFileName.txt         20,000                      300
Some Other Long FileName.txt   200,000                    3000

如果需要,您可以右对齐所有列。因此,将所有值设为负值会输出。

        ReallyLongFileName.txt               20,000        300
  Some Other Long FileName.txt              200,000       3000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多