Skip to main content
edited tags
Link
slm
  • 380.2k
  • 127
  • 793
  • 897
Source Link
Serge
  • 231
  • 2
  • 8

Batch file move to directory structure based on filename

I am writing a script to move files into directories based on the filename. Files have yyyyddmm-xxxxxxx.jpg name format. The desired directory structure is in the format 2013/01 Jan/31. I am unable to get date to format correctly with a space between month number and month name. When I try to use +%Y/%m %b format, I get this error message:

date: extra operand `%b"'

I tried double and single quotation marks, but to no avail. However, date +"%Y/%m %b/%d" works fine in sh:

2013/10/27 Oct

Also, is there a better way to generate the directory name than using MOVEDIRSTR and MOVEDIR variables (see script)?

Here's my current script:

FLIST=`ls "$IMGDIR" | grep -E '^.*\.jpg$'` # If there are files to move if [ -n "${FLIST}" ]; then # For each file while read -r line; do # Parse filename to YYYY/mm Mmm/Dd echo $line MOVEDIRSTR=`sed -r -e 's:([0-9]{4})([0-9]{2})([0-9]{2}).*:date -d \1-\2-\3 +%Y/%m_%b/%d:' <<< "$line"` MOVEDIR=`$MOVEDIRSTR` # If a directory does not exist, create it [ -d "$ARCHIVEDIR/$MOVEDIR" ] || (mkdir -p "$ARCHIVEDIR/$MOVEDIR") # Move file into YYYY/mm Mmm directory # mv -f "$IMGDIR/$line" "$ARCHIVEDIR/$MOVEDIR" done <<< "$FLIST" fi