1 Star 0 Fork 0

sierxue/scripts

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
move_files.sh 2.08 KB
一键复制 编辑 原始数据 按行查看 历史
sierxue 提交于 2024-01-29 12:42 . new: move_files.sh
#!/bin/bash
# move_files.sh
# https://app.yinxiang.com/shard/s22/nl/4928451/ed3df83d-22db-48f2-a2a0-7b890188baca
# This script moves files from a source directory to a destination directory
# based on a specified file pattern. It handles filenames with spaces and
# special characters correctly.
#
# Usage:
# ./move_files.sh <source_directory> <file_pattern> <destination_directory>
#
# Arguments:
# - source_directory: The directory where the files currently exist.
# - file_pattern: The pattern to match files (e.g., "*.txt" for all text files).
# - destination_directory: The directory where the files should be moved to.
#
# Example:
# ./move_files.sh ~/Downloads "*.pdf" ~/Documents/PDFs
#
# Note:
# The script checks for the existence of the source and destination directories
# and ensures that at least one file matches the pattern before attempting to move files.
move_files() {
# Check if the correct number of arguments is provided
if [ $# -ne 3 ]; then
echo "Usage: move_files <source_directory> <file_pattern> <destination_directory>"
return 1
fi
local src_dir=$1
local file_pattern=$2
local dest_dir=$3
# Check if the source directory exists
if [ ! -d "$src_dir" ]; then
echo "Source directory '$src_dir' not found."
return 1
fi
# Check if the destination directory exists
if [ ! -d "$dest_dir" ]; then
echo "Destination directory '$dest_dir' not found."
return 1
fi
# Using find with -exec to handle filenames with spaces and special characters
find "$src_dir" -maxdepth 1 -name "$file_pattern" -exec sh -c '
for file do
mv "$file" '"$dest_dir"' && echo "Moved: $file" || echo "Failed to move: $file"
done
' sh {} +
# Check if find command found any files
if [ $(find "$src_dir" -maxdepth 1 -name "$file_pattern" | wc -l) -eq 0 ]; then
echo "No files found matching the pattern '$file_pattern' in $src_dir."
return 1
else
echo "Move operation completed."
fi
}
# Calling the function with all passed arguments
move_files "$@"
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/sierxue/scripts.git
git@gitee.com:sierxue/scripts.git
sierxue
scripts
scripts
master

搜索帮助

D67c1975 1850385 1daf7b77 1850385