简体   繁体   中英

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

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM