【问题标题】:Moving multiple files in directory that might have duplicate file names移动目录中可能具有重复文件名的多个文件
【发布时间】:2013-11-27 08:19:52
【问题描述】:

谁能帮我解决这个问题?

我正在尝试将图像从我的 USB 复制到我计算机上的存档中,我决定制作一个 BASH 脚本来简化这项工作。我想复制文件(即 IMG_0101.JPG),如果存档中已经有一个具有该名称的文件(我每次使用它时都会擦拭相机),该文件应该命名为 IMG_0101.JPG.JPG 所以我不会丢失文件。

#method, then
mv IMG_0101.JPG IMG_0101.JPG.JPG
else mv IMG_0101 path/to/destination 

【问题讨论】:

  • 回滚了您上次的编辑,因为您大幅更改了问题,并将其变成了 your other question 的副本。

标签: linux bash shell scripting


【解决方案1】:
for file in "$source"/*; do
    newfile="$dest"/"$file"
    while [ -e "$newfile" ]; do
        newfile=$newfile.JPG
    done
    cp "$file" "$newfile"
done

这里存在竞争条件(如果另一个进程可以在第一个 donecp 之间创建同名文件)但这是相当理论上的。

想出一个不那么原始的重命名策略并不难;也许用增加的数字后缀加上.JPG替换末尾的.JPG

【讨论】:

  • 我同意,我会在最后添加几位数字,非常感谢您的帮助!
【解决方案2】:

使用文件的最后修改时间戳标记每个文件名,因此如果它是同一个文件,则不会再次复制它。

这是一个特定于 bash 的脚本,可用于将文件从“from”目录移动到“to”目录:

#!/bin/bash

for f in from/*
do
  filename="${f##*/}"`stat -c %Y $f`
  if [ ! -f to/$filename ]
  then
    mv $f to/$filename
  fi
done

这是一些示例输出(在名为“movefiles”的脚本中使用上述代码):

# ls from
# ls to
# touch from/a
# touch from/b
# touch from/c
# touch from/d
# ls from
a  b  c  d
# ls to
# ./movefiles
# ls from
# ls to
a1385541573  b1385541574  c1385541576  d1385541577
# touch from/a
# touch from/b
# ./movefiles
# ls from
# ls to
a1385541573  a1385541599  b1385541574  b1385541601  c1385541576  d1385541577

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2018-11-01
    相关资源
    最近更新 更多