Quote:
Originally Posted by chihung
We do not have to test for individual directory level 'cos if the bottom directory exists, the parent level should exist. Also, mkdir -p will make all the non-existing parent directories. Also, I introduce 'short circurt' && to ensure directory exist before I move the file.
We can also avoid all the repeating code using in extracting yy/mm/dd/hh by using 'set --' and sed. sed will change 2 digits with 2 digits + space so that it can put the result back to "set --" to set the positional variables accordingly
This is my contribution, it should work (even on sh)
Code:
for i in *.jpg
do
# yy is $1, mm is $2, dd is $3, hh is $4
set -- `echo $i | sed -e 's/\([0-9][0-9]\)/\1 /g'`
dir="$1/$2/$3/$4"
[ ! -d $dir ] && mkdir -p $dir && mv $i $dir
done
|
Your script is absolutely perfect, I love it ... except ...
the last --> [ ! -d $dir ] && mkdir -p $dir && mv $i $dir <-- wouldnt actually move the file if the directory existed already, so I added an extra line below with just --> mv $i $dir <-- in place and that solved that part, so it now becomes, although I would imagine this will now generate an error if the directory it wants to create doesnt exist (but shouldnt error for subsequent files - I think)
Code:
#!/bin/bash -x
for i in *.jpg
do
# yy is $1, mm is $2, dd is $3, hh is $4
set -- `echo $i | sed -e 's/\([0-9][0-9]\)/\1 /g'`
dir="$1/$2/$3/$4"
[ ! -d $dir ] && mkdir -p $dir && mv $i $dir
mv $i $dir
done