How to copy every file with extension X while keeping the original folder structure? (Unix-like systems)

时间:2018-03-25 19:35:03

标签: bash shell unix

I am trying to copy every HTML file from an src folder to a dist folder. However, I should like to preserve the original folder structure and if the dist folder does not exist I should like to create a new one.

Create the folder if it does not exist:

[ -d _dist/ ] || mkdir _dist/

Copy every file:

cp -R _src/**/*.html _dist/

Together:

[ -d _dist/ ] || mkdir _dist/ && cp -R _src/**/*.html _dist/

However, if I use ** only the files inside a folder will get copied and if I remove the ** only the root files will get copied. Is this even accomplishable?

2 个答案:

答案 0 :(得分:3)

find _src -type f -name "*.html" -exec cp -t _dist --parents {}  ";"
  • cp -t : target directory
  • --parents : append parents dir to target

This will omit empty (no html-files) dirs. But if you need them, repeat without -name "*.html" but with -type d.

答案 1 :(得分:0)

In the case you don't have a version of bash with the --parents option, cpio is awesome.

[ -d _dist/ ] || cd _src && find . -name '*.html' | cpio -pdm _dist && mv _dist ..

This would recursively copy all html files into _dist while maintaining the directory structures.

GNU cpio manual - GNU Project