我需要帮助。我必须使用批处理文件计算列.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 :(得分: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终止,但是&lt; 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%
答案 1 :(得分: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
。
用 nothing 替换行中的所有空格,逗号和分号。从理论上讲,您还需要替换 Tab - 公式为set "varname=%varname:replacethis=withthis%"
最后,用空格替换每个管道并计算结果的数量。