如果你愿意用所谓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
您的代码根本不适用于我。当我运行它时,我得到',* delims = 0“在这个时候是意外的。 – aphoria 2014-08-27 18:58:28