Linux cp with a regexp

Johy picture Johy · Aug 21, 2011 · Viewed 12.2k times · Source

I would like to copy some files in a directory, renaming the files but conserving extension. Is this possible with a simple cp, using regex ?

For example :

cp ^myfile\.(.*) mydir/newname.$1

So I could copy the file conserving the extension but renaming it. Is there a way to get matched elements in the cp regex to use it in the command ? If not, I'll do a perl script I think, or if you have another way...

Thanks

Answer

Kerrek SB picture Kerrek SB · Aug 21, 2011

Suppose you have myfile.a, myfile.b, myfile.c:

for i in myfile.*; do echo mv "$i" "${i/myfile./newname.}"; done

This creates (upon removal of echo) newname.a, newname.b, newname.c.