Home > Back-end >  Copy whole directory but exclude all folders and subfolders with certain name
Copy whole directory but exclude all folders and subfolders with certain name

Time:11-11

I'm not allowed to use rsync on the cluster I'm working on so I need to use cp. I want to copy a large directory including all files and subfolders etc. but without any folders that have the name "outdir". I tried cp -r -v ./!(outdir) ../target-directory/ but it still copies all folders and contents in deeper directories with the name outdir. It only included the outdir folders in the highest directory.

I also tried cp -r ./*/!(outdir) ../target-directory/ but that one copied all files into the folder without keeping any hirarchy or folders etc.

I also tried certain find commands but it didn't work, but maybe I was just doing something stupid. I'm a beginner with bash so if you could explain your answer and what the flags etc. do that would really be helpfull, I've been trying forever now, on what I think shouldn't be that hard to do.

CodePudding user response:

Instead of cp, you can use tar with option --exclude to control what you want copied or not.

The full command is:

tar --exclude="outdir" -cvpf - . | (cd TARGET_DIRECTORY; tar -xpf -)
  • So any path that contains the "outdir" pattern will be excluded.
  • Without the --exclude option, it will copy the entire structure of your current directory under TARGET_DIRECTORY.
  • You can replace the . in the first tar by your desired source directory.
  • Related