本文目录导读:

macOS 版本(使用 SetFile 命令)
#!/bin/bash
# 批量修改文件创建者和修改者 - macOS 版本
# 需要安装 Xcode 命令行工具
# 配置
CREATOR="YourCreatorName" # 创建者
FOLDER_PATH="." # 目标文件夹路径
# 检查 SetFile 是否可用
if ! command -v SetFile &> /dev/null; then
echo "错误: SetFile 命令不可用,请安装 Xcode 命令行工具"
exit 1
fi
# 遍历所有文件并修改属性
find "$FOLDER_PATH" -type f | while read -r file; do
echo "正在修改: $file"
SetFile -c "$CREATOR" "$file"
done
echo "完成!所有文件已修改。"
Linux/Unix 版本(使用 touch 命令)
#!/bin/bash
# 批量修改文件创建和修改时间 - Linux/Unix 版本
# 配置
NEW_USER="user1" # 新所有者
NEW_GROUP="group1" # 新用户组
MODIFY_DATE="2024-01-15 10:30:00" # 修改时间
ACCESS_DATE="2024-01-15 10:30:00" # 访问时间
FOLDER_PATH="${1:-.}" # 目标文件夹路径,可通过参数传入
# 修改文件所有者和组
find "$FOLDER_PATH" -type f -exec chown "$NEW_USER:$NEW_GROUP" {} \;
# 同时修改访问和修改时间
find "$FOLDER_PATH" -type f -exec touch -d "$MODIFY_DATE" {} \;
echo "完成!文件属性和时间戳已批量修改。"
更完善的跨平台脚本
#!/bin/bash
# 多功能文件属性批量修改脚本
show_help() {
echo "用法: $0 [选项]"
echo "选项:"
echo " -d, --directory 目标文件夹路径 (默认: 当前目录)"
echo " -u, --user 新所有者用户名"
echo " -g, --group 新用户组"
echo " -c, --creator 文件创建者标识"
echo " -t, --time 修改时间 (格式: 'YYYY-MM-DD HH:MM:SS')"
echo " -r, --recursive 递归处理子文件夹"
echo " -h, --help 显示帮助信息"
}
# 默认值
DIR="."
USER=""
GROUP=""
CREATOR=""
TIME=""
RECURSIVE=true
# 解析命令行参数
while [[ $# -gt 0 ]]; do
case $1 in
-d|--directory)
DIR="$2"
shift 2
;;
-u|--user)
USER="$2"
shift 2
;;
-g|--group)
GROUP="$2"
shift 2
;;
-c|--creator)
CREATOR="$2"
shift 2
;;
-t|--time)
TIME="$2"
shift 2
;;
-r|--recursive)
RECURSIVE=true
shift
;;
-h|--help)
show_help
exit 0
;;
*)
echo "未知选项: $1"
show_help
exit 1
;;
esac
done
check_system() {
case "$(uname -s)" in
Darwin)
SYSTEM="mac"
;;
Linux)
SYSTEM="linux"
;;
*)
echo "不支持的操作系统"
exit 1
;;
esac
}
modify_files() {
local path="$1"
local file_count=0
echo "正在处理文件夹: $path"
if [ "$RECURSIVE" = true ]; then
find_cmd="find $path -type f"
else
find_cmd="find $path -maxdepth 1 -type f"
fi
eval "$find_cmd" | while read -r file; do
# 检查文件权限
if [ ! -w "$file" ]; then
echo "警告: 没有写入权限,跳过 $file"
continue
fi
# 修改所有者
if [ -n "$USER" ]; then
chown "$USER" "$file"
echo " 修改所有者: $file -> $USER"
fi
# 修改用户组
if [ -n "$GROUP" ]; then
chgrp "$GROUP" "$file"
echo " 修改用户组: $file -> $GROUP"
fi
# 修改时间戳 (Linux)
if [ -n "$TIME" ] && [ "$SYSTEM" = "linux" ]; then
touch -d "$TIME" "$file"
echo " 修改时间戳: $file -> $TIME"
fi
# 修改创建者 (macOS)
if [ -n "$CREATOR" ] && [ "$SYSTEM" = "mac" ]; then
if command -v SetFile &> /dev/null; then
SetFile -c "$CREATOR" "$file"
echo " 修改创建者: $file -> $CREATOR"
else
echo "警告: SetFile 不可用,跳过创建者修改"
fi
fi
file_count=$((file_count + 1))
done
echo "处理完成,共修改 $file_count 个文件"
}
# 主程序
check_system
if [ ! -d "$DIR" ]; then
echo "错误: 文件夹不存在: $DIR"
exit 1
fi
echo "系统检测: $SYSTEM"
echo "目标文件夹: $DIR"
echo "开始批量修改文件属性..."
modify_files "$DIR"
echo "操作完成!"
Python 脚本(跨平台)
#!/usr/bin/env python3
"""
批量修改文件创建者和属性的 Python 脚本
跨平台支持 (Windows, macOS, Linux)
"""
import os
import sys
import shutil
import argparse
from datetime import datetime
from pathlib import Path
def modify_file_properties(file_path, user=None, group=None, time=None):
"""修改单个文件的属性"""
try:
# 修改访问和修改时间
if time:
timestamp = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
os.utime(file_path, (timestamp.timestamp(), timestamp.timestamp()))
print(f" 修改时间戳: {file_path}")
# 修改所有者(仅在 Unix 系统上)
if sys.platform != "win32":
if user:
os.chown(file_path, uid=os.getpwnam(user).pw_uid, gid=-1)
print(f" 修改所有者: {file_path}")
if group:
os.chown(file_path, uid=-1, gid=os.getgrnam(group).gr_gid)
print(f" 修改用户组: {file_path}")
return True
except Exception as e:
print(f" 错误处理 {file_path}: {e}")
return False
def batch_modify(directory, recursive=True, **kwargs):
"""批量修改目录中的文件属性"""
path = Path(directory)
file_pattern = "**/*" if recursive else "*"
files_modified = 0
errors = []
for file_path in path.glob(file_pattern):
if file_path.is_file():
success = modify_file_properties(str(file_path), **kwargs)
if success:
files_modified += 1
else:
errors.append(str(file_path))
print(f"\n操作完成!")
print(f"成功修改: {files_modified} 个文件")
if errors:
print(f"失败文件: {len(errors)} 个")
for err_file in errors[:5]:
print(f" - {err_file}")
def main():
parser = argparse.ArgumentParser(description="批量修改文件属性工具")
parser.add_argument("-d", "--directory", default=".",
help="目标文件夹路径 (默认: 当前目录)")
parser.add_argument("-u", "--user", help="新所有者用户名")
parser.add_argument("-g", "--group", help="新用户组")
parser.add_argument("-t", "--time", help="修改时间 (格式: 'YYYY-MM-DD HH:MM:SS')")
parser.add_argument("--no-recursive", action="store_false", dest="recursive",
help="不递归处理子文件夹")
args = parser.parse_args()
if not os.path.exists(args.directory):
print(f"错误: 文件夹不存在: {args.directory}")
sys.exit(1)
batch_modify(
args.directory,
recursive=args.recursive,
user=args.user,
group=args.group,
time=args.time
)
if __name__ == "__main__":
main()
使用示例
macOS:
# 修改所有文件的创建者为 "MyApp" ./modify_files.sh -c "MyApp" -d /path/to/folder # 修改文件时间和所有者 ./modify_files.sh -u newuser -g newgroup -d /path/to/folder -t "2024-01-15 10:30:00"
Linux:
# 批量修改所有者和时间 ./modify_files.sh -u newuser -g newgroup -d /path/to/folder -t "2024-01-15 10:30:00"
Python 版本:
# 使用 Python 脚本 python3 modify_files.py -d /path/to/folder -u newuser -t "2024-01-15 10:30:00" # 查看帮助 python3 modify_files.py --help
注意事项
- 权限要求:修改文件属性通常需要足够的系统权限,可能需要
sudo。 - 备份建议:执行前建议备份重要文件。
- 路径支持:请使用绝对路径或确保相对路径正确。
- 部分命令差异:macOS 和 Linux 的部分命令存在差异。
请根据您的操作系统和需求选择合适的脚本。