2

Say I have a listing of files with the same name, but different file extensions:

name.a
name.b
name.c
...
name.z

and want to rename them to:

newname.a
newname.b
newname.c
...
newname.z

How could I do this rename operation in one bash command?

Zéychin
  • 4,135
  • 2
  • 28
  • 27

2 Answers2

7

You can use rename utility:

rename 's/^name\./newname./' name.*
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This looks great and I am surprised I have not heard of `rename` before. (Guess my Google searches were too particular; all I saw was the `mv` command.) Thank you. I'll test it out and then I'll be back to accept this answer. – Zéychin Mar 27 '14 at 18:22
  • Hm. I tried this with the files I had in mind and it did not work, so I made two files, `name.a` and `name.b` and tested the command exactly as you wrote it. It does not rename the files. My regex is a bit rusty. Does anyone see the problem? – Zéychin Mar 27 '14 at 18:32
  • I did the same and tested this exact command and got files renamed. Result was `newname.a` and `newname.b` – anubhava Mar 27 '14 at 18:42
  • Very strange. It does not work for me. Thank you all the same. – Zéychin Mar 27 '14 at 19:50
  • Yes really weird. Can you do `type rename` and see what it shows. Also try: `rename 's/name\./newname./' name.*` – anubhava Mar 27 '14 at 19:54
  • `type` is not found and I do not have privileges to install new packages on this machine. That command also does nothing. – Zéychin Mar 27 '14 at 19:58
  • 2
    There are many variations of the `rename` command, if you're using the one that comes with the `perl` packages, this should work. If not it won't. Can easily check this by looking at the man page. – Reinstate Monica Please Mar 27 '14 at 20:01
  • Ah. Yes. That seems to be the problem. While I can not use this solution, it does appear to be the most elegant. Thank you. – Zéychin Mar 27 '14 at 20:08
1

You can use parameter expansion:

for f in name.*; do 
    ext="${f##*.}" 
    mv "$f" "newname.$ext"
done

There is an excellent write-up about it here

Timmah
  • 2,001
  • 19
  • 18