22

This is a simple question. I'm trying to copy all of the files in the current directory that start with axis-2 and end with .jar into a target directory, ~/MyDirectory.

My first attempt was

cp '^axis2.*jar$' ~/MyDirectory

... but when I try this, cp outputs a "No such file or directory" error message. I'm not sure I can use regular expressions with cp. I also haven't used regular expressions in a while, and my syntax could be off.

Does anyone have any suggestions on how to go about this?

5 Answers 5

24

The shell on Linux/UNIX systems uses glob patterns, not regular expressions. So, if you want to match file names starting with axis2 and ending with .jar, you could use:

cp axis2*.jar /destination/directory
0
16

If you have GNU find and GNU cp available, you can use regular expressions as in the following command:

find . -maxdepth 1 -regextype posix-basic -regex '.*/axis2[^/]*jar$' \
       -exec cp -t ~/MyDirectory {} +

This can be handy if neither glob pattern nor bash extended glob pattern suite your needs.

3

I really like the regex syntax of the rename perl script (by Robin Barker and Larry Wall), e.g.:

rename "s/OldFile/NewFile/" OldFile*

OldFile.c and OldFile.h are renamed to NewFile.c and NewFile.h, respectively

I simply wanted the exact same thing with a copy command:

copy "s/OldFile/NewFile/" OldFile*

So I duplicated that script and changed the rename statement to copy via File::Copy. Et voila! A copy command with perl-regex syntax: jcward/copy.

1

To use regular expressions in shell globs, you could use the ksh93 shell:

cp ~(E)^axis2.*jar$ ~/MyDirectory

(E for extended regexps. You can also use G for basic regexps, P for perl-like regexps, A/X for augmented regexps).

Or the zsh shell:

cp *(e['[[ $REPLY =~ "^axis2.*jar$" ]]']) ~/MyDirectory

That uses extended regexps unless you set the rematchpcre option in which case it uses perl-like regexps (as implemented by libpcre).

0

There is a command fd (sometimes named fdfind) that is a simple, user-frendly version of find.

With fd we can:

fd regexp             ... to get files matching regexp
... -x command        ... to execute `command` on the files

So I suggest something along the lines of:

fd '^axis2.*jar$'  -x cp -t ~/MyDirectory

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .