如何根据文件名将文件分类到文件夹中 - Windows CMD

Gil*_*ain 5 windows powershell command-line shell-script

如何使用 CMD / PowerShell 命令根据文件名将文件分类到文件夹中?

假设我有一个包含大量文件(超过 20,000 个文件)的文件夹,其中所有文件都具有相同的命名约定,例如:(注意模式)

t_1001_1801.png
t_1001_1802.png
t_1001_1803.png
...
t_1001_2112.png (last file starts with 't_1001_')
t_1002_1801.png
t_1002_1802.png
t_1002_1803.png
....
t_1002_2112.png
t_1003_1801.png
t_1003_1802.png
t_1003_1803.png
...
t_1214_2112.png (last file in folder)
Run Code Online (Sandbox Code Playgroud)

我运行这个 CMD 命令来创建一个文件夹列表:
for /l %i in (1001,1,1214) do md x%i
它创建一个文件夹列表,例如:

x1001
x1002
x1003
...
x1214
Run Code Online (Sandbox Code Playgroud)

现在我想根据文件名将文件排序(移动)到文件夹中,例如:

- move the files t_1001_1801.png to t_1001_2112.png to the folder x1001.
- move the files t_1002_1801.png to t_1002_2112.png to the folder x1002.
...
Run Code Online (Sandbox Code Playgroud)

我可以为此目的使用 shell 命令吗?

Sim*_*onS 8

您只需要拆分 FileName,获取数字(如 1001),将数字与文件夹进行比较,获取正确的文件夹并将文件移动到那里:

# Folder where Files and Folders are located
$TopFolder = "C:\Install"

# Getting Folders and Files
$Folders = gci $TopFolder -OutVariable Files | ? { $_.PSisContainer }

# Loop over all Files with *.png extension
$Files | ? { $_.Extension -eq '.png' } | % {

    # Split FileName to get the number (like 1001)
    $num = ($_.Name -split "_")[1]

    # Get FolderName by reading out foldername (without 'x') and compare it to number
    $MoveTo = $Folders | ? { $_.Name.substring(1,($_.Name.length -1)) -eq $num }

    # If a folder was found, move file there. else print error
    if ($MoveTo)
    {
        Move-Item $_.FullName $MoveTo -Force
        Write-Host "Copied File $($_.Name) to $MoveTo"
    }
    else 
    { 
        Write-Host "Did not find folder x$($num) in $TopFolder" 
    }
}
Run Code Online (Sandbox Code Playgroud)


Lot*_*ngs 7

以下批次

  • 更改要开始的文件夹
  • 使用 for 命令遍历所有 *.png 文件
  • 使用 for /f 将下划线处的名称拆分为标记,并使用第二个第三个标记
  • 检查带有编号的子文件夹 x 是否存在,如果不存在则创建
  • 最后将文件移动到子文件夹。

:: Q:\Test\2018\06\03\SU_1328200.cmd
@Echo off 
PushD "C:\Users\UserName\Pictures\"

For %%A in (t_*_*_*.png) do For /F "tokens=3delims=_" %%B in ("%%A") Do (
  If Not exist "x%%B" MD "x%%B"
  Move "%%A" "x%%B"
)
PopD
Run Code Online (Sandbox Code Playgroud)

运行批处理后的示例树 /F
(从第一个要求与第二个令牌过时)

> tree /F
????x1001
?       t_1001_1801.png
?       t_1001_1802.png
?       t_1001_1803.png
?       t_1001_2112.png
?
????x1002
?       t_1002_1801.png
?       t_1002_1802.png
?       t_1002_1803.png
?       t_1002_2112.png
?
????x1003
?       t_1003_1801.png
?       t_1003_1802.png
?       t_1003_1803.png
?
????x1214
        t_1214_2112.png
Run Code Online (Sandbox Code Playgroud)

一个 PowerShell 脚本:

## Q:\Test\2018\06\03\SU_1328200.ps1
PushD  "C:\Users\UserName\Pictures\"
Get-ChildItem t_*_*_*.png |
  Where BaseName -match 't_\d{2}_(\d{4})_\d{4}'|
    Group {'x'+$Matches[1]}|
      ForEach{MD $_.Name;$_.Group|Move -Dest $_.Name}
Run Code Online (Sandbox Code Playgroud)