我有一个文件 (file1.csv
),它有两个用逗号分隔的值。我需要一种方法来从一个批处理文件中的两个值中删除前导零。
到目前为止我用过这个:
@echo off
(for /f "tokens=*,* delims=0" %%a in (file1.csv) do echo(%%a)>stripped.txt
虽然它只从第一个数字而不是第二个数字中删除零,但它工作得很好。
来自 file1.csv
的示例:
00012345,00000012345
00067890,00000067890
使用上述批处理文件后 stripped.txt
中的示例:
12345,00000012345
67890,00000067890
有人对我如何对逗号后的数字做同样的事情有什么建议吗?
最佳答案
如果您愿意使用名为 REPL.BAT 的混合 JScript/批处理实用程序,那么解决方案可以很简单:
type file.csv|repl "0*(\d\d*),0*(\d\d*)" "$1,$2" >stripped.csv
这个 REPL.BAT 解决方案不仅简单,而且非常高效。它可以非常快速地处理大型 CSV。
如果您必须有一个纯批处理解决方案,那么这里有一个不使用 CALL 或 GOTO 或延迟扩展的解决方案,它可以正确处理 0 值。这将比 REPL.BAT 解决方案慢得多,但我认为这是最有效的纯批处理解决方案。
第一个循环将行解析为两个值。
然后每个值还有两个循环。第一个循环去除前导零,但它还在空格后附加一个额外的 0 值,以便它始终返回一个字符串,即使该值为 0。最后一个循环然后返回原始零去除值,或者如果它已经被因为它是 0 而被消除,然后它返回附加的 0 值。
@echo off
(for /f "delims=, tokens=1,2" %%A in (file.csv) do (
for /f "delims=0 tokens=*" %%C in ("%%A 0") do for /f %%E in ("%%C") do (
for /f "delims=0 tokens=*" %%D in ("%%B 0") do for /f %%F in ("%%D") do (
echo %%E,%%F
)
)
))>stripped.csv
去除前导零的代码可以封装在一个函数中,使用起来会更方便。如果要剥离的行中有许多值,则尤其如此。但是 CALL 机制相当慢。对于这个要剥离两个值的简单问题,它会使求解速度降低 5 倍以上。
@echo off
setlocal enableDelayedExpansion
(for /f "delims=, tokens=1,2" %%A in (file.csv) do (
call Strip0 %%A A
call Strip0 %%B B
echo !A!,!B!
))>stripped.csv
exit /b
:strip0 ValueStr [RtnVar]
::
:: Strip leading zeros from value ValueStr and store the result in vaiable RtnVar.
:: If RtnVar is not specified, then print the result to stdout.
::
for /f "delims=0 tokens=*" %%A in ("%~1") do for /f %%B in ("%%A 0") do (
if "%~2" equ "" (echo %%B) else set "%~2=%%B"
)
exit /b
有一种先进的批处理宏技术,可以将逻辑封装在宏函数中,而不会显着降低速度。参见 http://www.dostips.com/forum/viewtopic.php?f=3&t=1827有关带参数的批处理宏的背景信息。
这是一个使用批处理宏的解决方案。它比 CALL 方法快 4 倍。
@echo off
:: The code to define the macro requires that delayed expansion is disabled.
setlocal disableDelayedExpansion
call :defineStrip0
:: This example requires delayed expansion within the loop
setlocal enableDelayedExpansion
(for /f "delims=, tokens=1,2" %%A in (file.csv) do (
%strip0% %%A A
%strip0% %%B B
echo !A!,!B!
))>stripped.csv
exit /b
:defineStrip0 The code below defines the macro.
:: Define LF to contain a linefeed character (0x0A)
set ^"LF=^
^" The above empty line is critical - DO NOT REMOVE
:: Define a newline with line continuation
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
::%strip0% ValueStr [RtnVar]
::
:: Strip leading zeros from string ValueStr and return the result in variable StrVar.
:: If RtnVar is not specified, then print the result to stdout.
::
set strip0=%\n%
for %%# in (1 2) do if %%#==2 (setlocal enableDelayedExpansion^&for /f "tokens=1,2" %%1 in ("!args!") do (%\n%
for /f "delims=0 tokens=*" %%A in ("%%1") do for /f %%B in ("%%A 0") do (%\n%
endlocal^&if "%%2" equ "" (echo %%B) else set "%%2=%%B"%\n%
)%\n%
)) else set args=
exit /b
关于batch-file - 如何从逗号分隔文件中删除前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25534424/