How to move all the files with the same name scattered through the file system into one folder

command linefilesystemsfind

I have a file system tree and on different locations within it are files with the same name. I tried the following command on the command line:

find / -name "HAHA" -exec mv {} /home \;

It only worked for one file, for the others I received an error message for having the same name.

Can I change the command in a way that for each file name a number will be attached to distinguish them?

enter image description here

Best Answer

I found a simple solution with a small script. The script is called cpf (or whatever name you give it) and is as follows:

#!/bin/bash

dir=xyz       # Directory where you want the files
num=1

for file in "$@"
do
    base=`basename -- "$file"`
    mv -- "$file" "$dir/$base.$num"
    num=$(($num+1))
done

You execute the command as follows:

find . -name HAHA -print0 | xargs -0x cpf
Related Question