How can I copy multiple files in different directories using the Linux cp command?

Could you please help me figure out how to do this?

Let's say, under this directory:

/home/user1/

there are 100 folders, the name of these folders are 1, 2, 3 ... to 100. In each folder, there are 26 files.

  • The names of the files in folder 1 are 1a, 1b ... to 1z.
  • The names of the files in folder 2 are 2a, 2b ... to 2z.
  • The names of the files in folder 100 are 100a, 100b... to 100z.

How can I copy all the files ending with z to a new folder?

2 Answers

Use wildcards.

cp /home/user1/*/*z newfolder/

Some of the wildcards include *, ? and [].

* matches any number of characters which can be any character

? matches one character which can be any character

[] matches one character which is within the range of characters defined

Example:

[jin@crypt /tmp] % ls foo/*/*
foo/bar/1a foo/bar/1c foo/baz/1a foo/baz/1c foo/baz/2d foo/quux/1b foo/quux/1d
foo/bar/1b foo/bar/1d foo/baz/1b foo/baz/1d foo/quux/1a foo/quux/1c foo/quux/3d
[jin@crypt /tmp] % ls foo/*/*d
foo/bar/1d foo/baz/1d foo/baz/2d foo/quux/1d foo/quux/3d
[jin@crypt /tmp] % ls foo/ba?/*d
foo/bar/1d foo/baz/1d foo/baz/2d
[jin@crypt /tmp] % ls foo/ba??/*d
zsh: no matches found: foo/ba??/*d
[jin@crypt /tmp] % ls foo/baz/*[a-c]
foo/baz/1a foo/baz/1b foo/baz/1c

Use the find command:

find . -type f -name \*z -exec cp {} newfolder/ \;

That looks a bit complicated, so I'll break it down.

Find finds files, where you tell it and below. The dot by itself means 'current directory'. The next parameter '-type f' means 'find things of type file'. The '-name *z' means 'and things with a name that matches '*z'. Next, the '-exec cp {} newfolder/' means to execute the cp command on the found item - the command substitutes the matching filename for the {}. Finally, the '\;' terminates the exec command string - miss that and you'll get an error.

If you just want to see what files match, do this:

find . -type f -name \*z -print

That'll just print the matching files to the screen.

This should work in pretty much any Linux, UNIX, or Mac Terminal.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like