デジカメで撮影した画像ファイルを整理する際、撮影した日付ごとにディレクトリを作成し、その中に画像ファイルを保存している方も多いと思います。
このページでは、シェルスクリプトでファイルのタイムスタンプを判別し、それを同じ日付の付いたディレクトリに整理して保存する方法について説明します。
いきなり答えですが、以下のようなシェルスクリプト2つで上記の目的を達成することが出来ます。
#!/bin/sh binary_path=`dirname ${0}` source=${1} destination=${2} if [ -z ${source} ] then echo "Source is not specified, operation aborted." exit fi if [ ! -d ${source} ] then echo "Source is not a directory, operation aborted." exit fi if [ -z ${destination} ] then echo "Destination is not specified, operation aborted." exit fi if [ ! -d ${destination} ] then echo "Destination is not a directory, operation aborted." exit fi find -s ${source} -type f -iname "*.*" -exec ${binary_path}/subroutine.sh ${destination} {} \;
#!/bin/sh base=${1} target=${2} if [ -z ${base} ] then echo "Base is not specified, operation aborted." exit fi if [ ! -d ${base} ] then echo "Base is not a directory, operation aborted." exit fi if [ -z ${target} ] then echo "Target is not specified, operation aborted." exit fi if [ ! -f ${target} ] then echo "Target is not found, operation aborted." exit fi date=`stat -f %Sm -t %Y%m%d ${target}` if [ ! -d ${base}/${date} ] then mkdir ${base}/${date} fi mv ${target} ${base}/${date}
この2つのファイルの同じフォルダに格納し、「execute.sh」を下記のように実行させてください。
$ ./execute.sh /home/work/input/ /home/work/output/
上記の例では「/home/work/input/」およびそのサブフォルダ内にあるファイルを日付順に整理し、「/home/work/output/」に格納します。
「/home/work/output/」には、「/home/work/output/20091102/」のようなディレクトリが作成され、その中に「2009/11/02」のタイムスタンプのファイルが移動されます。(当該日付のファイルがひとつも存在しない場合、ディレクトリは作成されません)
シェルスクリプトが2つに分かれているのは、findの引数で呼ぶコマンドが、シェルスクリプトの関数に対応していない為です。(もしかしたら対応しているのかも知れませんが、私にはその方法を見つけられませんでした。)
もっとエレガントに実装する方法があれば、ぜひともこの下のコメント欄に解決方法を書いて教えてください!
・頂いたメッセージは管理者のチェックの後、公開されます。
・メッセージの公開を希望されない場合には、「このメッセージを非公開にする」にチェックを入れてください。
・管理者が不適切と判断したメッセージは公開しませんので、予めご了承ください。
まだ評価がありません |
表示できるメッセージはありません。