本文目录导读:

当然可以!实用脚本完全可以批量移动文件,批量移动是脚本最常用的功能之一,能帮你从重复的拖拽或复制粘贴中解脱出来。
下面给你提供几种常见场景的实用脚本,覆盖 Windows、macOS/Linux 以及 Python 通用方案。
Windows 环境 (PowerShell)
这是 Windows 10/11 最推荐的命令行方案,功能强大。
按扩展名移动(将所有 .jpg 和 .png 图片移到 图片 文件夹)
# 定义源文件夹和目标文件夹
$sourcePath = "C:\Users\你的用户名\Downloads"
$destPath = "C:\Users\你的用户名\Pictures"
# 获取所有 .jpg 和 .png 文件,然后移动到目标文件夹
Get-ChildItem -Path $sourcePath -Include "*.jpg", "*.png" -Recurse |
ForEach-Object { Move-Item -Path $_.FullName -Destination $destPath -Force }
-Recurse表示包含子文件夹中的文件。-Force表示如果目标已有同名文件则覆盖(谨慎使用)。
按文件名模式移动(将文件名包含 报告 的文件移走)
$source = "D:\工作文件" $dest = "D:\历史归档\报告" Get-ChildItem -Path $source -Filter "*报告*" | Move-Item -Destination $dest
将某个文件夹及其所有内容整体移动
Move-Item -Path "D:\临时\项目A" -Destination "D:\正式项目" -Force # 注意:这会移动整个 ProjectA 文件夹,成为 D:\正式项目\ProjectA
macOS / Linux 环境 (Bash / Zsh)
这是 Unix 系统最经典、最高效的方式。
移动特定日期后的文件(7天内修改过的 .txt 文件)
#!/bin/bash
find /path/to/source -name "*.txt" -mtime -7 -exec mv {} /path/to/destination/ \;
-mtime -7:修改时间在7天以内。find找到的每个文件。-exec命令结束符。
移动文件名包含特定字符串的文件
mv /source/folder/*2024* /dest/folder/ # 移动所有文件名包含 "2024" 的文件
移动大量文件(避免参数列表过长错误)
find /source -name "*.log" -print0 | xargs -0 -I {} mv {} /destination/
通用 Python 脚本 (跨平台)
如果你的需求比较复杂(如需要日志、更精细的错误处理、或跨平台运行),Python 是最佳选择。
import shutil
import os
from pathlib import Path
source_dir = Path("/path/to/source")
dest_dir = Path("/path/to/destination")
# 确保目标文件夹存在
dest_dir.mkdir(parents=True, exist_ok=True)
moved_count = 0
for file_path in source_dir.glob("**/*"): # **/* 递归所有文件
if file_path.is_file():
# 条件过滤:例如只移动大于 1MB 的 .pdf 文件
# if file_path.suffix == ".pdf" and file_path.stat().st_size > 1_000_000:
try:
shutil.move(str(file_path), str(dest_dir / file_path.name))
moved_count += 1
print(f"Moved: {file_path.name}")
except Exception as e:
print(f"Error moving {file_path.name}: {e}")
print(f"Total files moved: {moved_count}")
优点:可以轻松添加任何逻辑(如按文件大小、修改时间、创建日期、读取Excel表格中的文件名列表等)。
实用脚本的注意事项
-
千万别直接拷脚本运行:先把脚本中的路径换成你自己的。强烈建议先用
-WhatIf(PowerShell) 或echo(Bash) 模拟运行一下,看看会移动哪些文件,确认无误后再去掉测试参数。- PowerShell: 在
Move-Item后加-WhatIf。 - Bash: 把
mv换成echo mv。 - Python: 先只
print文件路径,不执行移动。
- PowerShell: 在
-
文件覆盖风险:大多数
Move-Item和mv命令,当目标存在同名文件时会直接覆盖,不会询问,如果确定要覆盖,可以使用;如果想避免,需要额外添加-NoClobber(PowerShell) 或-n(Bash mv) 或 Python 检查。 -
路径中的空格:如果路径或文件名包含空格,Windows 的 PowerShell 脚本通常不需要特别处理,但 Bash 中需要用引号包裹变量(如
"$file"),Python 则自动处理。 -
权限问题:确保你有源文件夹的读取权限和目标文件夹的写入权限。
- 简单、一次性任务:Windows 用 PowerShell,macOS/Linux 用 Bash 的
find+mv,通常一行搞定。 - 复杂、周期性任务:建议用 Python 脚本,可读性和健壮性更好。
- 追求极致安全:Always test with
-WhatIforechofirst!
如果你有更具体的需求(比如按Excel里的名单移动、按文件创建时间的精确范围移动等),可以把情况告诉我,我可以帮你定制更精准的脚本。