如何使用批处理文件计算文本文件中的字符数

时间:2015-03-17 15:50:09

标签: batch-file cmd

我想要计算某个文字的所有字符。但是在我的代码中它只计算单个字符串。但是要求需要计算所有字符,包括白色空格和新行。例如:

Hello World!
How are you today?
Hope you are okay

我将如何在我的代码中执行此操作?谢谢。 我的代码:

@ECHO OFF

for %%i in (y.txt) do @set count=%%~zi
REM Set "string" variable
SET string=(Hello World
            How are you today?
            Im fine..) // i want to read these string because my code only read single string
REM Set the value of temporary variable to the value of "string" variable
SET temp_str=%string%
REM Initialize counter
SET str_len=0

:loop
if defined temp_str (
REM Remove the first character from the temporary string variable and increment 
REM counter by 1. Countinue to loop until the value of temp_str is empty string.
SET temp_str=%temp_str:~1%
SET /A str_len += 1
GOTO loop
)

REM Echo the actual string value and its length.
ECHO %string% is %str_len% characters long!

2 个答案:

答案 0 :(得分:2)

这就是全部,你需要:

@ECHO OFF
set /p "file=enter filename: "
for %%i in (%file%) do @set count=%%~zi
echo this file has %count% characters including whitespaces and special chars like line-feed/carriage-return etc.

答案 1 :(得分:0)

使用此功能,您可以计算文本文件中的行号,单词数和字符数

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "MOD=%1"
SET "ARC=%2"
IF %MOD%==/L GOTO :CONTLIN
IF %MOD%==/P GOTO :CONTPAL
IF %MOD%==/C GOTO :CONTCAR
:CONTLIN
FOR /f "TOKENS=*" %%z IN (%ARC%) DO SET /a LINEAS+=1
ECHO %LINEAS%
EXIT /b 0
:CONTPAL
FOR /f "TOKENS=*" %%x IN (%ARC%) DO FOR %%y IN (%%x) DO SET /a PALABRAS+=1
ECHO %PALABRAS%
EXIT /b 0
:CONTCAR
SETLOCAL
FOR /f "TOKENS=*" %%a IN (%ARC%) DO (FOR %%b IN (%%a) DO (FOR %%a IN (%%b) DO (SET 
A=%%a)&(CALL :CC !A!)))
ECHO %CARACTERES%
EXIT /b 0
:CC
SET B=!A!
:I
SET /a CARACTERES+=1
SET B=%B:~1%
IF DEFINED B GOTO :I
EXIT /b 0

我可以从这样的文件中访问它:

@ECHO OFF
SET ARCHIVO=TEXTO.TXT
FOR /F %%a IN ('CONTTEXT /L %ARCHIVO%') DO SET /a LINEAS=%%a
FOR /F %%a IN ('CONTTEXT /P %ARCHIVO%') DO SET /a PALABRAS=%%a
FOR /F %%a IN ('CONTTEXT /C %ARCHIVO%') DO SET /a CARACTERES=%%a
ECHO %LINEAS% LINEAS
ECHO %PALABRAS% PALABRAS
ECHO %CARACTERES% CARACTERES
PAUSE