This should do (note that this is untested):
#!/bin/bash
BASE_DIR="/var/www/testing"
NEW_BASE_DIR="/var/www/testing/old"
FILE_EXTENSIONS_TO_MOVE="zip"
# If the new directory doesn't exist, create it
if [ ! -d ${NEW_BASE_DIR} ] ; then
echo "Creating ${NEW_BASE_DIR}"
mkdir ${NEW_BASE_DIR}
fi
echo "Moving files with extension .${FILE_EXTENSION} in ${BASE_DIR} to ${NEW_BASE_DIR}"
# For each file in BASE_DIR (there is probably a better way to do this ...)
for FILE in $(ls -1 ${BASE_DIR} | grep ".${FILE_EXTENSION}"); do
# First, get the file-name without extension
FILE_NAME=${FILE%.*}
NEW_FILE_EXTENSION=${FILE#.*}
# Extract the variant
PARTIAL_VARIANT=${FILE_NAME#_*}
VARIANT=${PARTIAL_VARIANT%-*}
# Extract the file's base name (before the underscore)
BASE_NAME=${FILE_NAME%_*}
# Extract the date (after the dash)
FILE_DATE=${FILE_NAME#-*}
# Now build the new path and file-name
NEW_DIR="${NEW_BASE_DIR}/${VARIANT}"
NEW_FILE_NAME="${BASE_NAME}_${VARIANT}_${FILE_DATE}.${NEW_FILE_EXTENSION}"
# Test if the directory exists
if [ ! -d ${NEW_DIR} ]; then
echo "Creating directory ${NEW_DIR}"
mkdir ${NEW_DIR}
fi
# Finally, move the file ...
echo "Moving ${BASE_DIR}/${FILE} to ${NEW_DIR}/${NEW_FILE_NAME}"
mv ${BASE_DIR}/${FILE} ${NEW_DIR}/${NEW_DIR}/${NEW_FILE_NAME}"
done
Input:
- /var/www/testing/FileName_s800-YYYYMMDD.zip
- /var/www/testing/FileName_s801-YYYYMMDD.zip
- /var/www/testing/FileName_s802-YYYYMMDD.zip
Output:
- /var/www/testing/old/s800/FileName_s800_YYYYMMDD.zip
- /var/www/testing/old/s801/FileName_s801_YYYYMMDD.zip
- /var/www/testing/old/s802/FileName_s802_YYYYMMDD.zip