How to copy every file with extension X while keep

2019-03-06 07:21发布

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?

标签: bash shell unix
2条回答
做自己的国王
2楼-- · 2019-03-06 08:21
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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-03-06 08:28

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

查看更多
登录 后发表回答