2013-11-27 27 views
0

任何人都可以帮助我解决这个问题吗?在具有重复文件名的目录中移动多个文件

我想从我的USB复制图像到我的电脑上的档案,我决定做一个BASH脚本,使这项工作更容易。我想复制文件(即IMG_0101.JPG),并且如果档案中已经有一个具有该名称的文件(每当我使用它时都会有我擦拭相机的情况),那么该文件应该命名为IMG_0101.JPG.JPG我不会丢失文件。

#!/bin/bash 

if [ $# -eq 0 ] 
then 
echo "Usage: $0 image_path archive_path" 
exit 999 
fi 

if [ -d "$1" ] #Checks if archive directory exists 
then 
echo Image Source directory FOUND 
else 
echo ERROR: Image Source directory has NOT BEEN FOUND 
fi 

if [ -d "$2" ] 
then 
echo Photo Archive FOUND 
else 
echo Creating directory 
mkdir "$2" 
fi 

    if [ find $1 -name "IMG_[0-9][0-9][0-9][0-9].JPG" ] #added this in to be more specific 1/4 
    then #2/4 
     for file in "$1"/* 
     do 

     dupefile= "$2"/"$file" 
      while [ -e "$newfile" ]; 
      do 
      newfile=$newfile.JPG 
      done 
     mv "$file" "$newfile" 
     done 
    else #3/4 
    #do nothing 
    fi #4/4 took all the /4 out, but it's saying theres no such file or directory, even though I've tested it and it says there is. 

意外的标记网络连接,我得到的错误,但如果语句需要在那里,所以我需要的特定文件,越来越移动。

+0

为什么不干脆前缀每everyfile与和索引号?或者你甚至可以用这个数字来替换整个名字,因为这个文件的名字对你来说并不重要。 –

+0

你应该确保你*不会*用'mv'覆盖任何现有的文件,甚至不是由于脚本中的错误。为此只需将选项'-n'添加到'mv'。 – scai

+0

你似乎混淆了'newfile'和'dupefile'。坚持一个或另一个。 – tripleee

回答

0

您不能有空的else。如果您没有else部件,请取出else关键字。你也应该摆脱多余的find。只需循环访问您实际需要的文件即可。

for file in "$1"/IMG_[0-9][0-9][0-9][0-9].JPG 
do 
    newfile= "$2"/"$file" 
    while [ -e "$newfile" ]; 
    do 
     newfile=$newfile.JPG 
    done 
    mv "$file" "$newfile" 
    done 
done 

(这也解决了dupefile VS newfile错误。)

+0

它现在说,没有这样的文件或目录,即使我已经进行了测试并且表示它们在那里... – user3038305

+0

修复了您的缩进,并且它将变得更容易看到属于哪个哪里。 – tripleee

+0

有一个额外的'做'在那里,它现在说mv:不能stat“$ 1(显然我的源文件夹,这是正确的,因为它被测试,但没有文件存在。)”/ IMG_ [0-9] [ 0-9] [0-9] [0-9] .JPG。我找到了$ 1 -name“IMG_ [0-9] .... JPG”-exec'{}'$ 2 \; <复制所有文件但不复制的工作,所以我知道新代码存在问题 – user3038305

相关问题