【问题标题】:Powershell: multiple wildcards in Get-ChildItem pathPowershell:Get-ChildItem 路径中的多个通配符
【发布时间】:2020-05-06 23:12:06
【问题描述】:

我正在尝试在 powershell 中使用 Get-ChildItem(我使用的是 ls 别名)仅返回特定文件夹结构中的文件。

例如,假设我试图列出名称以.foobar.txt 结尾的所有文件,这些文件位于名为src 的文件夹中,而该文件夹又位于名为even 的文件夹中。我试过使用命令ls -r *\even\src\*.foobar.txt | % FullName。我认为路径中的第一个通配符* 将允许任何以\even\src\ 结尾的路径,而第二个将只匹配以.foobar.txt 结尾的文件。但它并没有返回我期望的所有文件。这是我正在测试它的目录的结构:

root
|- project1
|  |- odd
|     |- src
|     |  |- a.foobar.txt
|     |  |- b.foobar.txt
|     |  |- c.snafu.txt
|     |
|     |- temp
|        |- a.foobar.txt
|        |- b.foobar.txt
|        |- c.snafu.txt
|
|- project2
|  |- folder1
|     |- folder2
|        |- folder3
|           |- folder4
|              |- even
|                 |- src
|                 |  |- a.foobar.txt
|                 |  |- b.foobar.txt
|                 |  |- c.snafu.txt
|                 |
|                 |- temp
|                    |- a.foobar.txt
|                    |- b.foobar.txt
|                    |- c.snafu.txt
|
|- project3
|  |- odd
|     |- src
|     |  |- a.foobar.txt
|     |  |- b.foobar.txt
|     |  |- c.snafu.txt
|     |
|     |- temp
|        |- a.foobar.txt
|        |- b.foobar.txt
|        |- c.snafu.txt
|
|- project4
   |- even
      |- src
      |  |- a.foobar.txt
      |  |- b.foobar.txt
      |  |- c.snafu.txt
      |
      |- temp
         |- a.foobar.txt
         |- b.foobar.txt
         |- c.snafu.txt

上述命令的输出是

root\project4\even\src\a.foobar.txt
root\project4\even\src\b.foobar.txt

但是,我期待

root\project2\folder1\folder2\folder3\folder4\even\src\a.foobar.txt
root\project2\folder1\folder2\folder3\folder4\even\src\b.foobar.txt
root\project4\even\src\a.foobar.txt
root\project4\even\src\b.foobar.txt

如何更改我的命令以便它也能在 project2 文件夹中找到文件?

【问题讨论】:

    标签: powershell wildcard directory-structure ls get-childitem


    【解决方案1】:

    正在考虑字符串匹配:

    gci * -R | ? { $_.FullName -like '*\even\src\*.foobar.txt' }
    

    【讨论】:

    • 两种解决方案都有效,但我更喜欢这个简单的解决方案。谢谢!
    • @inejwstine 是的,它会起作用,但可能会更慢,具体取决于您的目录树。但是,如果这对您来说很好,那就去吧。
    • 同意 - 它没有针对速度或内存进行优化。我主要考虑的是可读性。
    【解决方案2】:

    将其分为 2 个步骤。首先递归所有目录,过滤掉你想要的目录,然后通过另一个get-childitem 过滤掉你想要的文件名:

    ls -Recurse -Directory | where {$_.FullName -like "*\even\src"} | ls -filter  *.foobar.txt 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多