0

Following these two posts:

https://askubuntu.com/questions/871898/move-files-to-parent-directory-prefixing-file-name-with-former-subdirectory-nam

https://askubuntu.com/questions/870844/recursively-add-directory-name-to-file-name

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

1

2 Answers 2

1

Try:

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

Yields:

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.

0

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//\//-}"'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .