Moving multiple files in directory that might have

2019-02-27 16:32发布

can anyone help me with this?

I am trying to copy images from my USB to an archive on my computer, I have decided to make a BASH script to make this job easier. I want to copy files(ie IMG_0101.JPG) and if there is already a file with that name in the archive (Which there will be as I wipe my camera everytime I use it) the file should be named IMG_0101.JPG.JPG so that I don't lose the file.

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

2条回答
Anthone
2楼-- · 2019-02-27 17:15
for file in "$source"/*; do
    newfile="$dest"/"$file"
    while [ -e "$newfile" ]; do
        newfile=$newfile.JPG
    done
    cp "$file" "$newfile"
done

There is a race condition here (if another process could create a file by the same name between the first done and the cp) but that's fairly theoretical.

It would not be hard to come up with a less primitive renaming policy; perhaps replace .JPG at the end with an increasing numeric suffix plus .JPG?

查看更多
We Are One
3楼-- · 2019-02-27 17:22

Use the last modified timestamp of the file to tag each filename so if it is the same file it doesn't copy it over again.

Here's a bash specific script that you can use to move files from a "from" directory to a "to" directory:

#!/bin/bash

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

Here's some sample output (using the above code in a script called "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
查看更多
登录 后发表回答