【问题标题】:Count the number of lines of each text file in a given directory and store it in a variable计算给定目录中每个文本文件的行数并将其存储在变量中
【发布时间】:2015-11-24 11:00:57
【问题描述】:

我想计算给定目录中每个文本文件的行数并将它们存储在一个变量中。

这是我的代码:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /R "temp\textpipe_tmp\" %%U in (*.txt) DO (
    set "cmd=findstr /R /N "^^" "%%U" | find /C ":""
    for /f %%a in ('!cmd!') do set number=%%a
    echo %number%
)

:eof
pause

我不确定为什么它不起作用,但如果我摆脱 SET,它会起作用:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /R "temp\textpipe_tmp\" %%U in (*.txt) DO (
    findstr /R /N "^" "%%U" | find /C ":"
)

:eof
pause

我需要将结果存储在一个变量中。

【问题讨论】:

  • 更简单快捷的方法:find /v /c "" filename.ext,见an example。还有延迟扩展使用!number!,而不是%number%
  • 谢谢。延迟扩张的事情是罪魁祸首。

标签: windows batch-file cmd


【解决方案1】:

另一个版本,做同样的事情,但可读性稍好:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /R "C:\Users\Gebruiker\Documents\ICT" %%U in (*.txt) DO (
    set lines=0
    for /f  %%A in (%%U) do (set /a lines+=1)
    echo !lines!
)
pause

【讨论】:

  • 请记住for /F 会忽略空行,以及以; 开头的行(除非您更改默认选项eol=;)...
【解决方案2】:

正如@wOxxOm 在他的comment 中所说,find 是完成这项任务的完美选择。

假设有一个文件 test.txt 包含 12 行,find /V /C "" "C:test.txt" 将输出如下内容:

---------- C:TEST.TXT: 12

所以让我们使用for /F 循环来捕获这样的输出和字符串替换以获取:SPACE 之后的文本部分:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /R "temp\textpipe_tmp\" %%U in ("*.txt") do (
    rem capturing the output of `find` here:
    for /F "delims=" %%A in ('find /V /C "" "%%~U"') do (
        set "NUMBER=%%~A"
        rem substituting substring `: ` and everything before by nothing:
        set "NUMBER=!NUMBER:*: =!"
    )
    rem at this point, variable `NUMBER` is available
    rem for the currently processed file in `%%~U`:
    echo !NUMBER!
)
endlocal

请注意,如果文件的 end 处有空行(其中一个可能不包括在计数中),find /V /C "" 将返回意外结果。但是,将计算开头或非空行之间的空行。


更新:

使用> "C:test.txt" find /V /C "" 之类的重定向而不是find /V /C "" "C:test.txt" 可以避免前缀---------- C:TEST.TXT: 并且只返回行数(例如12)。通过此修改,无需进行字符串替换,因此代码如下所示:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /R "temp\textpipe_tmp\" %%U in ("*.txt") do (
    rem capturing the output of `find` here:
    for /F "delims=" %%A in ('^> "%%~U" find /V /C ""') do (
        set "NUMBER=%%~A"
    )
    rem at this point, variable `NUMBER` is available
    rem for the currently processed file in `%%~U`:
    echo !NUMBER!
)
endlocal

重定向标记<for /F中的in之后使用时,需要像^<一样进行转义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 2011-08-05
    • 2012-08-04
    • 1970-01-01
    相关资源
    最近更新 更多