我需要计算几个文件所具有的行数和列数。到目前为止,我设法获得行数
@echo off
if exist counts.txt del counts.txt
for /R "path To folder" %%a in (*.txt) do call :sub %%a
goto :eof
:Sub
for /F %%c in ('type "%*" ^| find /c /v ""') do set rowCount=%%c
echo %*;%rowCount% >> counts.txt
此批处理文件保存由;
分隔的文件名和行数。我坚持的是列数。有什么想法吗?
输出可能是
file path;row count;col count
答案 0 :(得分:1)
基本for
循环将未加引号的逗号,空格,制表符和分号作为分隔符进行计算。神奇的是,它会正确地跳过引用的逗号。要计算CSV文件中的列,您可以for %%I in (first line) do increment counter
。 这仅在您的csv标题行不包含未加引号的空格或其他分隔符时才有效。如果您更喜欢遵循原始逻辑并计算逗号数,请参阅下面的解决方案#2。
@echo off
setlocal
if exist counts.txt del counts.txt
for /R "path To folder" %%a in (*.txt) do call :sub "%%~fa"
goto :eof
:Sub
setlocal
for /F %%c in ('type "%~1" ^| find /c /v ""') do set rowCount=%%c
:: read first line of file.txt into var
set /P "line=" <"%~1"
:: delayed expansion prevents evaluation of special characters
setlocal enabledelayedexpansion
set count=0
for %%I in (!line!) do set /a count += 1
endlocal & set "colCount=%count%"
:: If you want to echo only filename.ext to counts.txt, un-rem this and
:: use %filename% instead of %~1 in your echo.
rem for %%I in ("%~1") do set "filename=%%~nxI"
echo %~1;%rowCount%;%colCount% >> counts.txt
endlocal
使用:length
函数获取带逗号和不带逗号的标题行的长度,并返回差值+ 1.(:length
函数逻辑基于jeb's :StringLength
。)< strong>仅当您的csv文件没有标题行,或者标题行保证不包含带引号的逗号时才会起作用。
@echo off
setlocal
if exist counts.txt del counts.txt
for /R "path To folder" %%a in (*.txt) do call :sub "%%~fa"
goto :eof
:Sub
setlocal
for /F %%c in ('type "%~1" ^| find /c /v ""') do set rowCount=%%c
:: read first line of file.txt into var
set /P "line=" <"%~1"
set colCount=0
:: delayed expansion prevents evaluation of special characters
setlocal enabledelayedexpansion
set line=!line:"=!
call :length b4 "!line!"
call :length after "!line:,=!"
endlocal & set /a colCount = %b4% - %after% + 1
:: If you want to echo only filename.ext to counts.txt, un-rem this and
:: use %filename% instead of %~1 in your echo.
rem for %%I in ("%~1") do set "filename=%%~nxI"
echo %~1;%rowCount%;%colCount% >> counts.txt
echo %~1;%rowCount%;%colCount%
endlocal
goto :EOF
:length <return_var> <string>
setlocal enabledelayedexpansion
set "tmpstr=%~2"
set ret=0
for %%I in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if not "!tmpstr:~%%I,1!"=="" (
set /a "ret += %%I"
set "tmpstr=!tmpstr:~%%I!"
)
)
endlocal & set "%~1=%ret%"
goto :EOF