user3375672
user3375672

Reputation: 3768

unix cp files from subfolders with pattern to new destination keeping subfolders

In unix. How can I copy files with a certain pattern ('pattern') to a new location keeping the subfolder structure:

/from/dir1name/a.pattern.b
/from/dir1name/c.pattern.d
/from/dir2name/e.pattern.f
/from/dir2name/g.pattern.h

Should be copied to :

 /to/dir1name/a.pattern.b
 /to/dir1name/c.pattern.d
 /to/dir2name/e.pattern.f
 /to/dir2name/g.pattern.h

Something along this will not keep the subfolder structure:

cp /from/*dir/*pattern* /to/

Do I need a loop to grasp the dir names (psuodocode):

for d in from/dir*; do cp "from/$d/*pattern*" "to/$d/"; done

This must have been asked before but I failed to find it on SO.

Upvotes: 0

Views: 661

Answers (1)

user2404501
user2404501

Reputation:

GNU cp has a --parents option that may be useful. cd /from ; cp --parents dir*/*pattern* /to/

You need to cd first so the part of the path you don't want replicated does not appear in the source arguments to cp.

There's no equivalent in traditional unix cp; you'll have to write your own loop and include mkdir commands for the intermediate levels, or cheat and use tar:

(cd /from ; tar cf - dir*/*pattern*) | (cd /to ; tar xvf -)

Upvotes: 1

Related Questions