
我有一個 FTP 進程,它不斷地將檔案放入目錄中。建立日期是檔案名稱的一部分,格式如下:
YYYY-MM-DD-HH-MM-SS-xxxxxxxxxxx.wav
我想根據文件的建立日期將文件移動到另一個目錄。我可以使用檔案名稱或日期戳,以更容易的為準。只需要考慮月份和年份。我使用以下格式建立了目錄:
Jan_2016
Feb_2016
我一直在手動建立目錄並移動文件,但我想使用 bash 腳本自動執行此操作,如果該目錄不存在,該腳本將建立該目錄。
到目前為止我一直在做的是手動建立目錄,然後執行以下命令:
MV ./2016-02*.wav Feb_2016/
答案1
### capitalization is important. Space separated.
### Null is a month 0 space filler and has to be there for ease of use later.
MONTHS=(Null Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
cd /your/ftp/dir ### pretty obvious I think
for file in *.wav ### we are going to loop for .wav files
do ### start of your loop
### your file format is YYYY-MM-DD-HH-MM-SS-xxxxxxxxxx.wav so
### get the year and month out of filename
year=$(echo ${file} | cut -d"-" -f1)
month=$(echo ${file} | cut -d"-" -f2)
### create the variable for store directory name
STOREDIR=${year}_${MONTHS[${month}]}
if [ -d ${STOREDIR} ] ### if the directory exists
then
mv ${file} ${STOREDIR} ### move the file
elif ### the directory doesn't exist
mkdir ${STOREDIR} ### create it
mv ${file} ${STOREDIR} ### then move the file
fi ### close if statement
done ### close the for loop.
對於沒有經驗的人來說,這應該是一個很好的起點。嘗試根據這些說明和命令編寫腳本。如果遇到困難,您可以尋求協助
答案2
這個腳本可能會有所幫助。 (請刪除實際 mv 檔案的回顯):
#!/bin/bash
shopt -s nullglob
month=(Jan Feb Mar May Apr Jun Jul Aug Sep Oct Nov Dec)
for y in 2016; do
for m in {01..12}; do
fn="$y-$m"
dn="${month[10#$m-1]}_$y"
[[ ! -d $dn ]] && mkdir -p "$dn"
for file in ./"$fn"*.wav; do
echo mv "$file" "./$dn/${file#\./}"
done
done
done