linux下面修改目录下所有文件时间

查看文件的时间:

stat test.txt

更新目录下面所有文件的时间:

find ./* -type f -exec touch {} \;

更新目录下面所有目录的时间:

find ./* -type d -exec touch {} \;

修改一个文件的日期时间:

touch -d "2020-11-11 11:00:00" test.txt

批量修改:

find ./* -exec touch -t 202011111100.00 {} \;

要批量修改目录下所有文件时间,可以借助多种编程语言或命令行工具来实现。下面是分别基于 Python、PowerShell 及 Linux Shell 的解决方案,并给出一些注意事项。 ### 1. **Python 实现** 利用 `os.walk()` 遍历整个目录树结构,然后对每个找到的文件应用时间修改操作。 ```python import os import time def batch_update_file_times(directory): for root, dirs, files in os.walk(directory): for file_name in files: file_path = os.path.join(root, file_name) # 获取当前时间作为新的时间戳 now_timestamp = int(time.time()) try: os.utime(file_path, (now_timestamp, now_timestamp)) print(f"{file_path}: 时间已成功更新.") except Exception as e: print(f"无法更新 {file_path}, 错误原因: {e}") if __name__ == "__main__": target_directory = input("请输入目标路径:") if not os.path.isdir(target_directory): print('无效的目标路径') else: batch_update_file_times(target_directory) ``` --- ### 2. **PowerShell 实现** 使用递归搜索和集合处理的方式轻松遍历指定文件夹内的全部项(含子级),逐一更改它们的属性值。 ```powershell $folderPath = Read-Host "输入文件夹位置" Get-ChildItem -Recurse -File $folderPath | ForEach { $_.LastWriteTime = [datetime]::Now Write-Output ("已将文件 " + $_.FullName + " 的最后一次编写时间更新为现在") } ``` --- ### 3. **Linux Shell Scripting 方式** 对于 Unix/Linux 系统用户来说,`find` 命令加上 `-exec touch {} \;` 结合起来非常高效且简洁地完成了这个需求。 ```bash #!/bin/bash read -p "Enter the directory to update timestamps: " dir find "$dir" -type f -exec touch '{}' + echo "All files within '$dir' have had their timestamps updated." ``` --- ### 注意事项: - 在执行此类脚本之前,请确保您有权限读取及写入所选文件夹及其内容。 - 测试阶段建议先在一个备份好的小样本集上运行以确认效果是否符合预期。 - 修改文件时间可能会影响到依赖于此元数据的应用程序的功能或是版本控制系统的行为,在实际环境中应小心行事。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值