Bash script for searching directory and moving files to a new directory, deleting any copies

…衆ロ難τιáo~ 提交于 2019-12-25 04:46:11

问题


I have a 2TB hard drive full of backed up data, including hundreds of movies, most of which have been copied several times due to sequential back-ups of the same HD. The hard drive is organized as a list of back-up folders, and every back-up contains a movies folder that has all the movies that were on my laptop HD at the time of the back-up.

I'd like to create a new movies folder and move all movies from every "movies" subfolder into the new one, making sure not to move the same movie twice. How can I go about this if I want to do everything via Bash?


回答1:


Assuming that each copy of a movie in various folders has the same name and all have the same extension, let's say .divx, you can use find to find them and copy them to a different folder and then delete the old folders.

find / -iname "*.divx" -type f -print0 | xargs -0 -I '{}' mv "{}" /path/to/new_folder/

Or you can loop through all the files and copy them to new_folder only if they are not already present. If already present, delete other copies. Something like this:

for file in $(find . -iname "*.divx" -type f)
do
filename=$(basename ${file})
if [ ! -f ./movie/${filename} ]; then
    mv ${file} ./movie/${filename}
else
    rm ${file}
fi
done


来源:https://stackoverflow.com/questions/22232430/bash-script-for-searching-directory-and-moving-files-to-a-new-directory-deletin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!