4

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 2

12

Using rsync with --exclude option.

rsync -av --exclude '*.txt' dir1/ dir2/
2
  • Let's say that after running the above command, I add a new file with .jpg extension to dir1. When I run your command again, does the command just adds .jpg file to dir2? Or the command copy again all the files in dir1 without .txt extention to dir2? Commented Dec 9, 2021 at 1:01
  • 1
    The 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. Commented Dec 9, 2021 at 7:22
3

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.