path/mydir包含目錄串列。這些目錄的名稱告訴我它們與哪個資料庫相關。
每個目錄里面都有一堆檔案,但檔案名告訴我什么都不重要。
我正在嘗試在 linux bash 中撰寫一個命令來完成以下操作:
- 對于 中的每個目錄
path/mydir,找到該目錄中最后修改檔案的最大時間戳 - 在父目錄名稱旁邊列印上次修改檔案的時間戳
- 排除任何小于 30 天的時間戳
- 使用正則運算式排除特定目錄名稱
- 按最早的時間戳排序
鑒于以下目錄結構path/mydir:
database_1
table_1.file (last modified 2021-11-01)
table_2.file (last modified 2021-11-01)
table_3.file (last modified 2021-11-05)
database_2
table_1.file (last modified 2021-05-01)
table_2.file (last modified 2021-05-01)
table_3.file (last modified 2021-08-01)
database_3
table_1.file (last modified 2020-01-01)
table_2.file (last modified 2020-01-01)
table_3.file (last modified 2020-06-01)
我想輸出:
database_3 2020-06-01
database_2 2021-08-01
這一半有效,但查看父目錄的修改日期而不是目錄下檔案的最大時間戳:
find . -maxdepth 1 -mtime 30 -type d -ls | grep -vE 'name1|name2'
我是 bash 的新手,因此非常感謝任何幫助和指導!
uj5u.com熱心網友回復:
請您嘗試以下操作
#!/bin/bash
cd "path/mydir/"
for d in */; do
dirname=${d%/}
mdate=$(find "$d" -maxdepth 1 -type f -mtime 30 -printf "%TY-%Tm-%Td\t%TT\t%p\n" | sort -rk1,2 | head -n 1 | cut -f1)
[[ -n $mdate ]] && echo -e "$mdate\t$dirname"
done | sort -k1,1 | sed -E $'s/^([^\t] )\t(. )/\\2 \\1/'
使用提供的示例輸出:
database_3 2020-06-01
database_2 2021-08-01
for d in */; do回圈遍歷path/mydir/.dirname=${d%/}洗掉尾部斜杠只是為了列印目的。printf "%TY-%Tm-%Td\t%TT\t%p\n"將修改日期和時間添加到由制表符分隔的檔案名中。結果將如下所示:
2021-08-01 12:34:56 database_2/table_3.file
sort -rk1,2按日期和時間欄位以降序對輸出進行排序。head -n 1選擇具有最新時間戳的行。cut -f1提取具有修改日期的第一個欄位。[[ -n $mdate ]]跳過空的mdate.sort -k1,1就在done對子目錄的輸出執行全域排序之后。sed -E ...交換時間戳和目錄名。它只考慮目錄名可能包含制表符的情況。如果沒有,可以sed通過切換命令中timestamp和dirname的順序,echo將sort命令改為sort -k2,2.
至于提到的Exclude specific directory names using regex,將您自己的邏輯添加到find命令或其他任何內容中。
[編輯]
為了在子目錄中最后修改的檔案早于指定日期時列印目錄名稱,請嘗試:
#!/bin/bash
cd "path/mydir/"
now=$(date %s)
for d in */; do
dirname=${d%/}
read -r secs mdate < <(find "$d" -type f -printf "%T@\t%TY-%Tm-%Td\n" | sort -nrk1,1 | head -n 1)
if (( secs < now - 3600 * 24 * 30 )); then
echo -e "$secs\t$dirname $mdate"
fi
done | sort -nk1,1 | cut -f2-
now=$(date %s)assigns the variablenowto the current time as the seconds since the epoch.for d in */; doloops over the subdirectories inpath/mydir/.dirname=${d%/}removes the trailing slash just for the printing purpose.-printf "%T@\t%TY-%Tm-%Td\n"prints the modificaton time as seconds since the epoch and the modification date delimited by a tab character. The result will look like:
1627743600 2021-08-01
sort -nrk1,1sorts the output by the modification time in descending order.head -n 1picks the line with the latest timestamp.read -r secs mdate < <( stuff )assignssecsandmdateto the outputs of the command in order.- The condition
(( secs < now - 3600 * 24 * 30 ))meets ifsecsis 30 days or more older thannow. echo -e "$secs\t$dirname $mdate"printsdirnameandmdateprepending thesecsfor the sorting purpose.sort -nk1,1just afterdoneperforms the global sorting across the outputs of the subdirectories.cut -f2-removessecsportion.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/358775.html
