
ファイルをディレクトリに常に保存する FTP プロセスがあります。作成日は次の形式でファイル名の一部になります。
YYYY-MM-DD-HH-MM-SS-xxxxxxxxx.wav
ファイルが作成された日付に基づいて、ファイルを別のディレクトリに移動したいと思います。ファイル名または日付スタンプのどちらか使いやすい方を使用できます。月と年のみを考慮する必要があります。次の形式を使用してディレクトリを作成しました。
Jan_2016
Feb_2016
これまでは手動でディレクトリを作成し、ファイルを移動していましたが、ディレクトリが存在しない場合にディレクトリを作成する bash スクリプトを使用してこれを自動化したいと考えています。
これまで私が行ってきたのは、手動でディレクトリを作成し、次のコマンドを実行することです。
mv ./2016-02*.wav 2016年2月/
答え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