Following these two posts:



I would like to do the same but with copying instead of moving. So simply, I have a directory containing subdirectories and subsubdirectories, where there are some files inside. I want to copy all the files to a another destination folder, but since some files have exact names, so I want to attach the name of the parent directories as a prefix to the filenames.

I am running on ubuntu 16.04


2 Answers 2



find  -name "*.dat" -exec bash -c 'echo cp "$1" "$(sed -e s:/:-:g -e s:^.-:./: <<<"$1")"' tinyscript {} \;

(remove the "echo" if the commands look good)

└── 1
    └── 2
        ├── 3
        │   └── 4
        │       └── foo.dat
        └── foo.dat


cp ./1/2/3/4/foo.dat ./1-2-3-4-foo.dat
cp ./1/2/foo.dat ./1-2-foo.dat

Basically you run an ad-hoc small script (cp "$1" "$(sed -e s:/:-:g -e s:^.-:./: <<<"$1")" on each file that matches and this script generates the target name by replacing all / in the source path by a -. The tinyscript string can be anything, it is just a name that is used as the script name in case of errors.


Favouring simplicity over performance, this is not particularly efficient (due to starting a bash process for each file). If you have a lot of files and/or time is a factor, a more involved solution may be needed.

find yourdirectory/ -type f -print0 | xargs -0 -I% bash -c 'F="%" ; echo cp "${F}" "${F//\//-}"'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.