如何更改文件的修改/建立日期?

如何更改文件的修改/建立日期?

有沒有辦法更改檔案修改/建立的日期(在 Nautilus 中或使用 ls -l 指令顯示)?理想情況下,我正在尋找一個命令,它可以將一大堆文件的日期/時間戳更改為提前或推遲一定時間(例如+8小時或-4天等)。

答案1

只要您是文件的擁有者(或 root),就可以使用以下命令更改文件的修改時間touch

touch filename

預設情況下,這會將檔案的修改時間設為當前時間,但有許多標誌,例如-d選擇特定日期的標誌。例如,要將檔案設定為在當前兩小時前修改,您可以使用以下命令:

touch -d "2 hours ago" filename

如果您想相對於其現有修改時間修改文件,則可以執行以下操作:

touch -d "$(date -R -r filename) - 2 hours" filename

如果要修改大量文件,可以使用以下命令:

find DIRECTORY -print | while read filename; do
    # do whatever you want with the file
    touch -d "$(date -R -r "$filename") - 2 hours" "$filename"
done

您可以將參數變更為find僅選擇您感興趣的文件。

find DIRECTORY -exec touch -d "2 hours ago" {} +

這種形式對於文件時間相對版本來說是不可能的,因為它使用 shell 來形成touch.

就創建時間而言,大多數 Linux 檔案系統不會追蹤該值。有一個ctime與文件關聯的,但它追蹤文件元資料上次更改的時間。如果檔案的權限從未更改過,則它可能會碰巧保留創建時間,但這是巧合。明確更改檔案修改時間算元資料更改,因此也會產生更新ctime.

答案2

最簡單的方法 - 存取和修改將是相同的:

touch -a -m -t 201512180130.09 fileName.ext

在哪裡:

-a = accessed
-m = modified
-t = timestamp - use [[CC]YY]MMDDhhmm[.ss] time format

如果您想使用,NOW只需刪除-t和 時間戳即可。

要驗證它們是否都相同: stat fileName.ext

看:男人觸摸

答案3

謝謝您的幫忙。這對我有用:

在終端機中前往日期編輯目錄。然後輸入:

find -print | while read filename; do
    # do whatever you want with the file
    touch -t 201203101513 "$filename"
done

按下回車鍵後,您將看到一個“>”,除了最後一次 ->“完成”。

注意:您可能需要更改“201203101513”

"201203101513" = 是您想要此目錄中所有檔案的日期。

答案4

這個小腳本至少對我有用:

#!/bin/bash

# find specific files
files=$(find . -type f -name '*.JPG')

# use newline as file separator (handle spaces in filenames)
IFS=$'\n'

for f in ${files}
do
 # read file modification date using stat as seconds
 # adjust date backwards (1 month) using date and print in correct format 
 # change file time using touch
 touch -t $(date -v -1m -r $(stat -f %m  "${f}") +%Y%m%d%H%M.%S) "${f}"
done

相關內容