I have two directories dir1 and dir2. I want to copy all the files and folders in dir1 to dir2 except the files that have .txt extension. How I can do this?
2 Answers
Using rsync with --exclude option.
rsync -av --exclude '*.txt' dir1/ dir2/
-
Let's say that after running the above command, I add a new file with
.jpgextension todir1. When I run your command again, does the command just adds.jpgfile todir2? Or the command copy again all the files indir1without.txtextention todir2?Admia– Admia2021-12-09 01:01:31 +00:00Commented Dec 9, 2021 at 1:01 -
1The extension is irrelevant. Rsync has many (many!) flags and options that can customize it's behavior, but usually, by default it just copies the differences. So in your case, it will copy only the new jpg file to dir2, or any other files that exist in dir1 and don't exist on dir2 (except for what you exclude, of course), or any changes in the content or attributes in any file from dir1 to dir2. Rsync first compares those dirs, and only then copies the delta.aviro– aviro2021-12-09 07:22:19 +00:00Commented Dec 9, 2021 at 7:22
POSIXly:
cd dir1 && LC_ALL=C pax -rwpe -'s|.*\.txt||' . ../dir2
Beware that at least with the implementation from http://www.mirbsd.org/pax.htm (as found on MirBSD or in the pax package on Debian for instance), it also excludes symlinks whose target ends in .txt even if the symlinks names themselves don't end in .txt.
Another difference with rsync is that though it excludes directories whose name ends in .txt, it doesn't exclude non-txt files in those directories. Add a -s'|.*\.txt/.*||' to also exclude those.
-pe tries to preserve as much metadata as possible (the list of which varies with the pax implementation). With rsync, see the -a (-rlptgoD), -AXUHN options to select what you want preserved.