文件批量拷贝的脚本(尤其适用于大小写敏感向不敏感的磁盘拷贝时发生冲突的情形)

发布时间 2024-01-08 19:30:23作者: Certainly

在Linux系统下,NTFS可以支持文件名大小写区分;但在MaxOS的exFAT格式中,则无法区分大小写。

当从NTFS向exFAT拷贝文件时,当同一个目录下而在文件名相同但大小写不同的两个及以上文件时,向exFAT写入会中断,使得文件拷贝操作无法完成。

因此,特别编写了下面这个脚本,用来解决这个问题。

它可以实现的功能包括:

(1)递归操作,只需要指定外部的文件路径即可;

(2)文件路径不变,有空格也会保留;

(3)如果遇到同名文件,会在文件名最后加1-10之间的数字(最大编号到10),后缀不变;

(4)如果文件名含有空格,会统一替换成下划线。

脚本文件 cp_dir.sh 的内容如下:

#! /bin/bash
# automatically copy files, and rename the file with case-nonsensitive environment under exFAT.
# edited by She, 2024-01-08
#
function cp_dir() { echo $1 $2 cur_dir="$1" for file in $(ls "$1" | tr " " "\?"); do echo file here: ${file} # filenew=`tr "\?" "_" <<<${file}` file=`tr "\?" " " <<<$file` filenew=$file if [ -d "$1"/"${file}" ]; then echo cp_dir "$1"/"${file}" echo mkdir -p "$2"/"${filenew}" mkdir -p "$2"/"${file}" cp_dir "$1"/"${file}" "$2"/"${filenew}" else echo "is file: " "$1"/"${file}" if [ ! -f "$2"/"${file}" ]; then echo "copy file one by one: " "$1"/"${file}" " --> " "$2"/"${filenew}" cp "$1"/"${file}" "$2"/"${filenew}" else # duplicate file, need to add the i-th before the appendicy. prefix=${file%.*} prefix=`tr " " "_" <<<${prefix}` app=${file##*.} for i in $(seq 1 10 1 ) do echo "i: " $i filenew=${prefix}${i}.${app} if [ ! -f "$2"/"${filenew}" ]; then echo "copy duplicate file: " "$1"/"${file}" "$2"/"${filenew}" cp "$1"/"${file}" "$2"/"${filenew}" break; else echo "skip the existed filename: " "$2"/"${filenew}" fi done fi fi done } cp_dir "$1" "$2" #SrcPath=$HOME/Downloads #DesPath=$HOME/Test2024 # cp_dir $SrcPath $DesPath

 

在终端运行命令:

chmod a+x ./cp_dir.sh

SrcPath=$HOME/Downloads
DesPath=$HOME/Test2024
cp_dir $SrcPath $DesPath