日付またはファイル名に基づいてファイルを移動するスクリプトの作成

日付またはファイル名に基づいてファイルを移動するスクリプトの作成

ファイルをディレクトリに保存し続ける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.

経験のない人にとっては、これが良い出発点になります。これらの指示とコマンドに基づいてスクリプトを作成してください。詰まったら助けを求めることができます

おすすめ記事