我有幾個按年 月 日期格式命名的檔案。
例子:
20220101 20220102 20220103 20220104 .. 20220130 20220131
作為每天生成的檔案,我需要每個月在特定檔案夾中移動第一個 2(20220101,20220102) 和最后一個 2(20220130,20220131) 檔案。有人可以幫助我如何撰寫腳本嗎?
uj5u.com熱心網友回復:
這幫助了我很久 -
#!/bin/bash
DIR=/Users/limeworks/Downloads/target
target=$DIR
cd "$DIR"
for file in *; do
# Top tear folder name
year=$(stat -f "%Sm" -t "%Y" $file)
# Secondary folder name
subfolderName=$(stat -f "%Sm" -t "%d-%m-%Y" $file)
if [ ! -d "$target/$year" ]; then
mkdir "$target/$year"
echo "starting new year: $year"
fi
if [ ! -d "$target/$year/$subfolderName" ]; then
mkdir "$target/$year/$subfolderName"
echo "starting new day & month folder: $subfolderName"
fi
echo "moving file $file"
mv "$file" "$target/$year/$subfolderName"
done
uj5u.com熱心網友回復:
好吧,如果您想在 bash 中執行此操作,我建議您使用一個腳本檔案和一個日志檔案來跟蹤當前月份/上個月。
#!/bin/bash
x=$(date %D | cut -c 4,5 | sed 's|0||g')
y=$(sed -n 1p date.log 2>/dev/null)
if ! [ -d date.log ]; then
printf "$x" > date.log
exit 0
fi
if [[ $y -ge 0 && $y -le 12 && $x != $y ]]; then
#if the current month equal the previous month then everthing here will be exicuted
echo "a new month is here"
else
sed -i "1s/^.*$/$x/" date.log
fi
這個腳本的本質是它創建包含當前月份的日志檔案“如果它不存在并且”。在“如果再次執行”之后,它將新的月份值與日志檔案中包含的月份值匹配,如果它不匹配,它將執行注釋文本所在的所有內容,這很可能是一堆 mv 命令。
uj5u.com熱心網友回復:
試試這個Shellcheck -clean 代碼:
#! /bin/bash -p
datefiles=( 20[0-9][0-9][01][0-9][0-3][0-9] )
mv -n -v -- "${datefiles[@]:0:2}" "${datefiles[@]: -2}" /path/to/folder
datefiles=( 20[0-9][0-9][01][0-9][0-3][0-9] )在當前目錄中創建一個具有日期格式名稱的檔案陣列,按名稱排序。"${datefiles[@]:0:2}"展開到datefiles陣列中的前兩個元素。"${datefiles[@]: -2}"展開到datefiles陣列中的最后兩個元素。- 你需要改變
/path/to/folder。 - 除非絕對保證始終至少有 4 個日期檔案,否則您應該添加對找到的檔案數量的檢查(例如。
if (( ${#datefiles[*]} >= 4 )) ...)。
uj5u.com熱心網友回復:
$ string="20220101 20220102 20220103 20220104 .. 20220130 20220131"
$ awk '{ print |"mv " $1" "$2" "$(NF-1)" "$NF " /your/folder"}' <<<"$string"
或者
$ myArray=(20220101 20220102 20220103 20220104 .. 20220130 20220131)
$ mv ${myArray[0]} ${myArray[1]} ${myArray[-2]} ${myArray[-1]} /your/folder
檔案到陣列
$ myArray=($(find /path/to/files -mindepth 1 -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" -print0))
或者
$ readarray myArray < <(find /path/to/files -mindepth 1 -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487303.html
上一篇:Bash:如果滿足某些條件并且該行在匹配之間,則從行中洗掉最后一個字符
下一篇:使用SED修復新行
