gpt4 book ai didi

linux - 拥有一个包含同名不同文件的文件夹

转载 作者:太空狗 更新时间:2023-10-29 11:14:46 25 4
gpt4 key购买 nike

我正在尝试仅将原始文件从一个目录复制到另一个目录,但有些文件具有相同的名称...我正在尝试使用哈希来比较文件,如果它不在目录中,则将其发送到那里,如果名称是同样将其更改为 file_name.something。此时我得到了一些文件,并且具有相同名称的文件正在被覆盖...任何人都可以提出建议吗?

#!/bin/bash -xv

source_folder=$1
destination_folder=$2

if [ $# -eq 0 ]
then
echo "usage:$0 directory_name";exit 999;
fi

if [ -d $source_folder ]
then
echo "source source_folder exists."
else
echo "Source folder doesn't exist"
exit 1;
fi

if [ -d $destination_folder ]
then
echo "Destination folder exists"
else
mkdir $destination_folder
fi



find "$source_folder" -name "IMG_[0-9][0-9][0-9][0-9].JPG" -exec ./check {} $destination_folder/ \;





#!/bin/bash -xv

file=$1
destination_folder=$2
file_hash=`md5sum "$file" | cut -d ' ' -f 1`

for a in $destination_folder/*
do
curr_hash=$(md5sum "$a" | cut -d ' ' -f 1)
curr_file=$a

if [ ! "$file_hash" == "$curr_hash" ];
then
if [[ -f $destination_folder/$file ]] ;
then # CAN ANYBODY TELL ME WHY IT IGNORES THIS LINE
cp "$file" "$file.JPG"
mv "$file.JPG" "$destintion_folder"
else # IT GOES STRAIGHT FOR THIS ONE
cp "$file" "$destination_folder"
fi
fi

done

最佳答案

您的 if [ "$file_hash"== "$a"]; 将哈希值与文件名进行比较。你需要类似的东西

if [ "$file_hash" == $(md5sum "$a" | cut -d ' ' -f 1) ];

计算目标文件夹中每个文件的哈希值。

此外,您的 for 循环在当前版本中只运行一次;你需要类似的东西

for a in $destination_folder/*

获取该文件夹中的所有文件,而不仅仅是文件夹名称。

根据您的编辑,解决方案如下所示

#!/bin/bash -xv

file=$1
destination_folder=$2
file_hash=`md5sum "$file" | cut -d ' ' -f 1`

# test that the filename exists in the destination dir
if [[ -f $destination_folder/$file ]] ; then
dest_hash=$(md5sum "$destination_folder/$file" | cut -d ' ' -f 1)
# test that the hash is the same
if [[ "$file_hash" == $curr_hash ]] ; then
cp "$file.JPG" "$destination_folder/$file.JPG"
else
# do nothing
fi
else
# destination does not exit, copy file
cp "$file.JPG" "$destination_folder/$file"
fi

这并不能确保没有重复。它只是确保具有相同名称的不同文件不会相互覆盖。

#!/bin/bash -xv

file=$1
destination_folder=$2
file_hash=`md5sum "$file" | cut -d ' ' -f 1`

# test each file in destination
for a in $destination_folder/*
do
curr_hash=$(md5sum "$a" | cut -d ' ' -f 1)
if [ "$file_hash" == $curr_hash ];
then
# an identical file exists. (maybe under another name)
# do nothing
exists=1
break
fi
done

if [[ $exists != 1 ]] ; then
if [[ -f $destination_folder/$file ]] ; then
cp "$file.JPG" "$destination_folder/$file.JPG"
else
cp "$file.JPG" "$destination_folder"
fi
fi

未测试。

关于linux - 拥有一个包含同名不同文件的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19961306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com