Using regular expressions with cp
Solution 1
The UNIX shell uses glob patterns, not regular expressions. So, if you want to match file names starting with axis2
and ending with .jar
, you use:
cp axis2*.jar /destination/directory
Solution 2
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.
Solution 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
andOldFile.h
are renamed toNewFile.c
andNewFile.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.
Nick Van Hoogenstyn
Updated on September 18, 2022Comments
-
Nick Van Hoogenstyn almost 2 years
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, let's say it's ~/MyDirectory. My first thought was to try
cp '^axis2.*jar$' ~/MyDirectory
But this isn't working. I'm not even sure I can use regular expressions with cp. I also haven't really used regular expressions in a while and my syntax could be totally off. When I try this cp just outputs a "No such file or directory" error message. Does anyone have any suggestions of how to go about this? Thanks!
-
Nick Van Hoogenstyn over 12 yearsThanks a lot! I figured it out on my own, but I didn't know about glob patterns so that's helpful and informative.