Moving multiple files in directory that might have duplicate file names

前端 未结 2 580
滥情空心
滥情空心 2021-01-27 00:31

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 t

相关标签:
2条回答
  • 2021-01-27 00:37
    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?

    0 讨论(0)
  • 2021-01-27 00:40

    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
    
    0 讨论(0)
提交回复
热议问题