2017-03-05 34 views
-1

我需要帮助。我必须使用批处理文件来计算列.txt。列由“|”分隔 我想这一点:统计文件列数

@echo off 

set file=C:\Users\Documents\test\days.txt 

for /F "delims==|" %%a in ('type "%file%" ^|find "" /v /c') do set contColumns=%%a  

echo This file %file% have %contColumns% columns. 

PAUSE 
+0

这将有助于我们了解输入文件的细节。每行的列数也是一样的吗? _只读第一行比阅读all_更好。 – Compo

回答

2

下面将计算|在你的文件的第一行中分隔列数。这只适用于行长度为< = 1021,行数为Windows格式(以\ r \ n结尾)而非Unix格式(以\ n结尾)。

@echo off 
setlocal enableDelayedExpansion 
set "file=C:\Users\Documents\test\days.txt" 

:: Read the first line 
set "ln=" 
<"%file%" set /p "ln=" 

:: Convert columns into lines by substituting .\n. for every | 
if defined ln set ^"ln=.!ln:^|=.^ 
%= This equates to a newline (\n) character =% 
.!^" 

:: Count the number of lines and store the result 
for /f %%N in ('cmd /v:on /c echo(^^!ln^^!^|find /c /v ""') do set "cnt=%%N" 

echo line 1 column count = %cnt% 

如果行可以超过1021或不被\ r \ n终止,但< 8191,然后

@echo off 
setlocal disableDelayedExpansion 
set "file=C:\Users\Documents\test\days.txt" 

:: Read the first line 
for /f usebackq^ delims^=^ eol^= %%A in ("%file%") do (
    set "ln=%%A" 
    goto :endLoop 
) 
:endLoop 

:: Convert columns into lines by substituting .\n. for every | 
setlocal enableDelayedExpansion 
if defined ln set ^"ln=.!ln:^|=.^ 
%= This equates to a newline (\n) character =% 
.!^" 

:: Count the number of lines and store the result 
for /f %%N in ('cmd /v:on /c echo(^^!ln^^!^|find /c /v ""') do set "cnt=%%N" 

echo line 1 column count = %cnt% 
0
@ECHO OFF 
SETLOCAL 
SET "sourcedir=U:\sourcedir" 
SET "filename1=%sourcedir%\q426111659.txt" 

:: get first line 
SET /p line=<"%filename1%" 

:: remove all spaces, commas and semicolons 
SET "line=%line: =%" 
SET "line=%line:,=%" 
SET "line=%line:;=%" 
:: convert all pipes to spaces and count 
SET /a count=0 
FOR %%a IN (%line:|= %) DO SET /a count+=1 

ECHO %count% columns IN file 


GOTO :EOF 

你需要改变的sourcedir设置,以满足您情况。

我使用了一个名为q426111659.txt的文件,其中包含一些用于测试的虚拟数据。

将文件的第一行读入line

替换所有空格,逗号和分号。从理论上讲,你需要更换标签以及 - 计算公式为set "varname=%varname:replacethis=withthis%"

最后,用空格替换每个管和计数令牌的结果数量。