Bash – Wildcard Expansion

bashwildcard

I'm not really sure how to phrase this, and maybe that's why I can't find anything, but I want to reuse the values enumerated by a wildcard in a command. Is this possible?

Scenario:

$ ls /dir
1 2 3

Contents of /dir are directories 1, 2, and 3.

$ cp /dir/*/file .

Results in file being copied from /dir/1 /dir/2 and /dir/3 to here.

What I would like to do is copy the files to a new destination name based on the wildcard expansion.

$ cp /dir/*/file ???-file would result in /dir/*/file being copied to 1-file, 2-file, and 3-file. What I can't figured out is the ??? portion to tell Bash I want to use the wildcard-expanded values.

Using the wildcard in the target nets a cp error:

cp: target `*-file' is not a directory.

Is there something else in Bash that can be used here?

The find command has {} to use with -exec which is similar to what I am looking for above.

Best Answer

ls /dir |while read dirname; do cp -v /dir/"$dirname"/file "$dirname"-file ; done