CMD树命令限制层数

问题描述 投票:0回答:8

如何限制Windows中tree命令经过的层数?我需要将结果输出到文本文件中进行工作,但由于默认情况下,tree 命令列出了运行该命令的目录下的每个目录,因此我得到的输出超过 44,000 行长,这没有帮助完全为了我的工作。我如何将其限制为仅列出前几个级别?

windows cmd tree
8个回答
27
投票

实际上,DOS 和 Windows 中的

tree
命令没有指定命令所经过的目录级别的选项。您可以参考Microsoft Docs上的tree文档

但是您可以使用 Git Bash 代替。当您安装Git for Windows时会提供此工具。 这样一来,你就可以使用@Zhengquan Feng提到的命令这是一个被删除的答案

tree -L 3 // three levels show

26
投票

因为我在这里没有找到完整的答案。这是:

Windows CMD 不支持

-L
深度级别。

  1. 安装 CygWin https://www.cygwin.com.
  2. 在 Cygwin 中,确保选择已安装的实用程序/树包。
  3. 打开 CygWin 并导航到您的文件夹,例如 cd
    ../../cygdrive/c/myFolder
  4. 列出树结构并保存为result.txt
    tree -L 3 >result.txt
    .

14
投票
  1. 尝试在您的Windows系统中下载WSL

  2. 在命令提示符中:

    bash

  3. 然后你可以使用Linux命令,这个例子是针对3级别深:

    tree -L 3


5
投票

您可以在 Windows 上尝试这个项目:

https://github.com/MrRaindrop/tree-cli

用途:

使用

-l
levelNumber 指定路径级别:

treee -l 2


4
投票

示例 3 个级别:

tree|findstr /v /r /c:"^........│" /c:"^│....... " /c:"^ ....... "

4
投票

如果您使用 WSL,您还可以将结果直接导出到 Windows 剪贴板

  • 从 WSL Cline,如果您尚未安装
    tree
    sudo apt install tree
  • 然后:
    tree -L 5 | clip.exe
    (将
    5
    替换为您想要的深度)

这将绕过将其保存到 txt 文件并直接转到剪贴板以快速粘贴到论坛等。


4
投票

我知道这个问题很老了,但是在 Powershell 中:

(我知道,它需要一些清理,为最终用户隐藏变量等......但它无需安装任何东西即可工作)

$sb = New-Object System.Text.StringBuilder

Function Get-Tree {
    Param ([String]$Path, [Int]$LevelMax, [Int]$Level = 0, [Bool]$LastOfTheList=$true, [String]$Lead="")

    if ($Level -eq 0) {$sb.AppendLine($Path)}
    if ($Level -eq $LevelMax) { Return }

    $Lead = if($LastOfTheList){"$Lead   "}else{"$Lead$([char]0x2502)  "}

    [Array]$Liste = $Path | Get-ChildItem -Directory

    For($x=0;$x -lt $Liste.count;$x++) {
        $item = $Liste[$x]
      
        if ($x -eq $Liste.Count-1) { 
            $sb.AppendLine("$($Lead)$([char]0x2514)$([char]0x2500)$([char]0x2500)$($item.Name)") | Out-Null 
            Get-Tree -Path $item.Fullname -level ($level +1) -LevelMax $LevelMax -Lead $Lead -LastOfTheList $true
        }
        else { 
            $sb.AppendLine("$($Lead)$([char]0x251c)$([char]0x2500)$([char]0x2500)$($item.Name)") | Out-Null 
            Get-Tree -Path $item.Fullname -level ($level +1) -LevelMax $LevelMax -Lead $Lead -LastOfTheList $false
        }
    }
}

Get-Tree -Path "MyPath" -LevelMax 3
$sb.ToString() | Out-File "MyOutputFile.txt" -Encoding UTF8

0
投票

限制级别数(1)

在CMD中,可以使用

DIR /B

仅显示当前目录级别的文件和文件夹名称。


在PowerShell中,类似的命令是:

Get-ChildItem -Name
© www.soinside.com 2019 - 2024. All rights reserved.