在目录中移动可能具有重复文件名的多个文件

时间:2013-11-27 08:19:52

标签: linux bash shell scripting

任何人都可以帮我这个吗?

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

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

2 个答案:

答案 0 :(得分:1)

for file in "$source"/*; do
    newfile="$dest"/"$file"
    while [ -e "$newfile" ]; do
        newfile=$newfile.JPG
    done
    cp "$file" "$newfile"
done

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

提出一个不太原始的重命名政策并不难;也许最后使用增加的数字后缀加上.JPG替换.JPG

答案 1 :(得分:0)

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

这是一个特定于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