简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM