Roma Shultz
Roma Shultz

Reputation: 13

find and copy files and directories

I'm trying to create bash script that will copy files that was created or modificated in last 24 hours. I know that isnot a new question, but i cant find answers that can help me. So i have dir test (all files/dir of them is created in last 24 h).

test/
    file1.txt
    file2.txt
    dir/
             file.txt

How can i copy them in format like this:

backup/
      file1.txt
      file2.txt
      dir/
               file.txt

Because if i use find test -type f -ctime -1 -exec cp -r {} backup \;

backup/
      file.txt
      file1.txt
      file2.txt

or find test -exec -ctime -1 cp -r {} backup \;:

backup/
    file.txt
    file1.txt
    file2.txt
    test/
             file1.txt
             file2.txt
             dir/
                      file.txt
    dir/
             file.txt

Upvotes: 1

Views: 93

Answers (1)

oguz ismail
oguz ismail

Reputation: 50815

A bit hackish and probably slow due to bash but, this should do the trick:

find test -type f -mtime -1 -exec bash -c '
    src=("$@")
    dst=("${@/#test/backup}")
    mkdir -p "${dst[@]%/*}"
    for i in "${!src[@]}"; do
        cp "${src[i]}" "${dst[i]}"
    done
' _ {} +

_ at the end is a placeholder for $0 (you know $@ expands to $1, $2, ...).

For a dry-run insert echo before mkdir and cp.

Upvotes: 1

Related Questions