【问题标题】:Windows command to get list of file extensions获取文件扩展名列表的 Windows 命令
【发布时间】:2017-05-19 14:02:33
【问题描述】:

我需要一个命令来获取文件夹中不同的扩展文件以及每个扩展的出现次数。

那么我该怎么做呢?

【问题讨论】:

    标签: windows batch-file cmd filesystems file-attributes


    【解决方案1】:

    您可以使用这样的 PowerShell 单行代码:

    powershell "$ext = @{}; gci *.* | %{ $ext[$_.Extension]++ }; $ext"
    

    如果在 .bat 脚本中使用它,请将 % 符号加倍。


    在纯批处理中,这是我能想到的最简单的方法:

    @echo off & setlocal
    
    for %%I in (*.*) do (
        set /a ext[%%~xI] += 1
    )
    
    set ext[
    

    或浓缩为单行文字(仍在 .bat 脚本中):

    @setlocal & @(for %%I in (*.*) do @set /a ext[%%~xI] += 1) & set ext[
    

    或者直接从 cmd 控制台:

    cmd /c ">NUL (@for %I in (*) do @set /a ext[%~xI] += 1) & set ext["
    

    cmd /c 的行为类似于 bat 脚本中的 setlocal,可帮助您避免使用无用的变量破坏您的环境。)

    【讨论】:

    • 谢谢最后一个命令对我有用,但我需要一种迭代方式,我需要子文件夹中的所有文件扩展名
    • @LamloumiAfif 在.bat 方法中,使用for /R 进行递归。在 PowerShell 方法中,只需将 -recurse 开关添加到 gci 命令即可。要包含隐藏/系统文件,批量使用for /f "delims=" %%I in ('dir /s /b /a:-d') 等。在PowerShell 中,将-force 选项添加到gci
    • +1,不需要ext[...]。您可以简单地使用set /a "%%~xI+=1",然后使用set . 来查看结果。理想情况下,您应该在顶部放置 SETLOCAL。此外,用for /f "delims==" %%V in ('set .') do set "%%V=" 之类的东西清除任何现有的.ext[ 变量也没有什么坏处。无论哪种方式,如果扩展包含数学运算符,如+-^ 等,这种计数方法都会失败。
    • 糟糕,我错了。如果文件没有扩展名,则使用 %%~xI 作为变量名失败:-(
    【解决方案2】:

    这是来自superuser.com 的解决方案。将此代码保存在 .bat 文件中。

    @echo off
    
    set target=%~1
    if "%target%"=="" set target=%cd%
    
    setlocal EnableDelayedExpansion
    
    set LF=^
    
    
    rem Previous two lines deliberately left blank for LF to work.
    
    for /f "tokens=*" %%i in ('dir /b /s /a:-d "%target%"') do (
        set ext=%%~xi
        if "!ext!"=="" set ext=FileWithNoExtension
        echo !extlist! | find "!ext!:" > nul
        if not !ERRORLEVEL! == 0 set extlist=!extlist!!ext!:
    )
    
    echo %extlist::=!LF!%
    
    endlocal
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 2012-06-07
      • 2016-09-01
      • 1970-01-01
      相关资源
      最近更新 更多