2
\$\begingroup\$

This following code searches for jpg files of size larger than 500 KB. Its purpose is to move/cp files, depending on their EXIF data, into folders that correspond to the files' year and month.

find . -type f -iname '*.jpg' -size +500k | while read file; do
 yr=$(stat -f '%Sm' -t '%Y' "$file")
 month=$(stat -f '%Sm' -t '%m' "$file")
 folder="/path/to/backup/folder/$yr"
 subFodler=$folder"/"$month
 [[ -d "$folder" ]] || echo mkdir "$folder"
 [[ -d "$subFodler" ]] || echo mkdir "$subFodler"
 echo mv "$file" "$folder/$month"
done

Currently it ́s a lot of duplicate lines.

Stephen Rauch
4,31412 gold badges24 silver badges36 bronze badges
asked Jun 30, 2019 at 12:23
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Trivial code typo note: subFodler is a misspelling of subFolder. Glenn Jackman's solution gets rid of this variable, but just for the record... \$\endgroup\$ Commented Jun 30, 2019 at 13:33

1 Answer 1

2
\$\begingroup\$

I see this invocation of stat is MacOS specific.

Here's how I would shrink your code

find . -type f -iname '*.jpg' -size +500k -exec sh -c '
 for file in "$@"; do
 folder="/path/to/backup/folder/$(stat -f '%Sm' -t '%Y/%m' "$file")"
 mkdir -p "$folder"
 echo mv "$file" "$folder"
 done
' sh {} +

mkdir -p will create all missing folders, and it will also suppress errors if the directory already exists.

find's -exec cmd {} + feeds several filenames to the given command.

And this looks odd sh -c 'stuff' sh file ... -- the 2nd sh will be assigned to 0ドル inside the -c script, and the given files will be 1,ドル 2,ドル etc.

answered Jun 30, 2019 at 12:33
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice! Thanks! add a " to line 4, at the mkdir line and we are good to go! \$\endgroup\$ Commented Jun 30, 2019 at 14:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.