Bash 脚本将某些文件移动到特定目录?

Bash 脚本将某些文件移动到特定目录?

我正在寻找一个可以将文件从一个目录移动到另一个目录的脚本,但是每个文件都有不同的名称,并且其名称对应于应该移动到的文件夹。

例如:

  • 文件 1:var/www/testing/FileName_s800-date.zipvar/www/testing/old/s800/

  • 文件 2:var/www/testing/FileName_s801-date.zipvar/www/testing/old/s801/

s800s801等是所述文件的变体,应该定义该文件进入哪个文件夹)

答案1

应该这样做(请注意,这尚未测试):

#!/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

输入:

  • /var/www/testing/FileName_s800-YYYYMMDD.zip
  • /var/www/testing/FileName_s801-YYYYMMDD.zip
  • /var/www/testing/FileName_s802-YYYYMMDD.zip

输出:

  • /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

相关内容