【问题标题】:Moving multiple files in directory that have duplicate file names [duplicate]移动目录中具有重复文件名的多个文件[重复]
【发布时间】:2013-11-27 09:37:41
【问题描述】:

谁能帮我解决这个问题?

我正在尝试将图像从我的 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. 

unexpected token fi 是我得到的错误,但 if 语句需要在那里,所以我需要的特定文件正在移动。

【问题讨论】:

  • 为什么不简单地在每个文件前加上索引号?或者你甚至可以用这个数字替换整个名称,因为文件名对你来说似乎并不重要。
  • 您应该确保您从不使用mv 覆盖任何现有文件,即使是由于脚本中的错误。为此,只需将选项 -n 添加到 mv
  • 你好像把newfiledupefile搞混了。坚持一个或另一个。
  • 您应该在exit 分支中使用非零结果代码ERROR。但是,您不能使用大于 255 的结果代码。

标签: linux bash shell scripting


【解决方案1】:

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 错误。)

【讨论】:

  • 现在说没有这样的文件或目录,即使我已经进行了测试并且它说它们在那里......
  • 修复你的缩进,它会变得更容易看到什么属于哪里。
  • 那里有一个额外的'done',现在它说 mv: cannot stat "$1(显然我的源文件夹,这是正确的,因为它经过测试但不存在文件。)"/ IMG_[0-9][0-9][0-9][0-9].JPG。我有 >find $1 -name "IMG_[0-9]....JPG" -exec '{}' $2 \;
  • 谁能告诉我为什么需要在引号中包含一些变量有些不需要?我知道美元被用作替代品,但为什么要引号?
  • 基本上,除非您特别希望外壳程序将您的变量拆分为空格,否则请使用引号。单引号提供最大的保护,双引号允许变量扩展等。这不是FAQ
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2015-02-28
  • 2017-05-08
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多