0

I have a series of files which differ in extension (for example, a.txt, a.ps, a.pdf, etc.) and would like to copy them to a series of new files with a different name (b.txt, b.ps, b.pdf, etc.), preferably using terminal as I am running all other necessary operations from there. Years ago, I used to be able to do this on a PC from command prompt quite simply with:

copy d.* a.*

while in the working directory.

I'm having trouble figuring out/finding the corresponding OSX command. Feel like I am missing something obvious here, but just cannot sort it out.

Help much appreciated. Thanks for your time.

1 Answer 1

1

This command would seem to do what you wish

for file in *.* ; do cp $file ${file//a\./b\.} ; done

Adapted from this answer to Renaming part of a filename

Actually, you could just do:

for file in * ; do cp $file ${file//a\./b\.} ; done

Note that the . has to be escaped using \.. This is primarily because your example is a filename of a single letter, which could potentially conflict with a letter in the extension.

If your filenames are a bit more explicit, such as doggy.txt, doggy.pdf, doggy.xls, etc., and you want to change them to feline.txt, feline.pdf, ..., etc., then you could do away with escaping the . (and the . all together), like so:

for file in * ; do cp $file ${file//doggy/feline} ; done

Note that the commands above will create a copy of the files, i.e.:

% ls
a.pdf   a.txt   a.xls   b.pdf   b.txt   b.xls

If you wish to just rename them, then use mv instead:

for file in * ; do mv $file ${file//a\./b\.} ; done

or

for file in * ; do mv $file ${file//doggy/feline} ; done
4
  • 1
    Also, unless you want to replace all matches, you should use ${file/a/b}, this will also solve the suffix problem.
    – nohillside
    Commented Jun 6, 2023 at 6:28
  • 1
    Or even ${file/#a/b} to match from the beginning (# plays the same role here as ^ in grep).
    – nohillside
    Commented Jun 6, 2023 at 6:29
  • 1
    Ah, and apply double quotes, you never know whether people have space characters in their filenames.
    – nohillside
    Commented Jun 6, 2023 at 6:32
  • This does exactly what I was looking for, thanks so much! Is there a way to make it quicker (maybe with an alias?) and more general? For example, in modeling some data, it's useful for me to make a number of these (dog.* to cat.*, dog.* to bird.* etc. so that I can keep dog.* while testing things with cat.*, bird.* etc.). The dream is something that can take ?.* (where ? will vary, not always dog) and easily make cat.*, bird.*, etc (number will vary). Looking for the OSX version of the PC copy file1.* file2.* , copy file1.* file3.* etc. Thanks again for your quick and helpful reply earlier!
    – rmjmu
    Commented Jun 6, 2023 at 8:03

You must log in to answer this question.

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