本文目录导读:

Windows (PowerShell)
按文件名模式移动
# 移动所有 .txt 文件到目标文件夹
Get-ChildItem -Path "C:\Source" -Filter "*.txt" | Move-Item -Destination "C:\Destination"
# 移动包含特定关键词的文件
Get-ChildItem -Path "C:\Source" | Where-Object {$_.Name -like "*report*"} |
Move-Item -Destination "C:\Destination"
按文件列表移动
# 从文本文件读取文件名列表并移动
$fileList = Get-Content "C:\filelist.txt"
foreach ($file in $fileList) {
if (Test-Path "C:\Source\$file") {
Move-Item "C:\Source\$file" "C:\Destination" -Force
}
}
Linux/macOS (Bash)
按扩展名移动
#!/bin/bash
# 移动所有 .jpg 文件
mv /source/*.jpg /destination/
# 移动多个指定扩展名
for ext in "pdf" "doc" "txt"; do
mv /source/*.$ext /destination/
done
按文件名模式移动 (使用find)
#!/bin/bash
# 移动文件名包含"2024"的文件
find /source -type f -name "*2024*" -exec mv {} /destination/ \;
# 移动大于10MB的文件
find /source -type f -size +10M -exec mv {} /destination/ \;
从列表文件移动
#!/bin/bash
while IFS= read -r filename; do
if [ -f "/source/$filename" ]; then
mv "/source/$filename" "/destination/"
echo "已移动: $filename"
else
echo "未找到: $filename"
fi
done < filelist.txt
Python (跨平台)
import os
import shutil
import glob
# 方式1: 按文件模式匹配
source_dir = r'/path/to/source'
dest_dir = r'/path/to/destination'
# 移动所有 .csv 文件
for file in glob.glob(os.path.join(source_dir, '*.csv')):
shutil.move(file, dest_dir)
# 方式2: 从文件列表移动
with open('filelist.txt', 'r') as f:
files_to_move = [line.strip() for line in f]
for filename in files_to_move:
src_path = os.path.join(source_dir, filename)
if os.path.exists(src_path):
shutil.move(src_path, dest_dir)
else:
print(f'文件不存在: {filename}')
# 方式3: 按条件过滤
import datetime
# 移动修改时间在24小时内的文件
cutoff = datetime.datetime.now() - datetime.timedelta(days=1)
for filename in os.listdir(source_dir):
filepath = os.path.join(source_dir, filename)
if os.path.isfile(filepath):
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(filepath))
if mtime > cutoff:
shutil.move(filepath, dest_dir)
高级批量移动示例
保留目录结构移动
#!/bin/bash
# Linux: 只移动文件,但保留相对路径
find /source -type f -name "*.txt" | while read file; do
relpath="${file#/source/}"
dirpath="/destination/$(dirname "$relpath")"
mkdir -p "$dirpath"
mv "$file" "$dirpath"
done
带日志和错误处理
import os
import shutil
import logging
logging.basicConfig(filename='move_log.txt', level=logging.INFO)
def batch_move(source, destination, pattern):
success = 0
failed = 0
for file in os.listdir(source):
if pattern in file:
src = os.path.join(source, file)
dst = os.path.join(destination, file)
try:
shutil.move(src, dst)
logging.info(f'成功移动: {file}')
success += 1
except Exception as e:
logging.error(f'移动失败: {file} - {str(e)}')
failed += 1
print(f'完成: {success}个成功, {failed}个失败')
# 使用
batch_move('/source', '/destination', '.pdf')
使用建议
-
先测试:先用
echo或-WhatIf参数预览- PowerShell:
Move-Item -Destination ... -WhatIf - Linux: 先用
ls查看匹配的文件
- PowerShell:
-
备份:移动前确保有备份或使用复制测试
-
权限:确保对源和目标目录有读写权限
-
路径处理:注意路径中的空格和特殊字符
需要哪种操作系统的具体例子?我可以提供更详细的适配版本。