I have a directory ~/mydir/ with many files. Some of these files are


I'd like to change any file in ~/mydir/ whose base name is foo to foo-bar. So, the files above should be renamed as


I am not worried about the new file names conflicting with existing files ($ ls ~/mydir/foo-bar* returns nothing).

It seems like this should be easy to do in bash, but I can't figure it out.

Is there a simple script to accomplish this task?


2 Answers 2


If your distribution uses (or offers) the perl version of rename (Debian and most derivatives do):

cd mydir
rename 's/\.([^.]+)$/-bar.$1/

I know some distributions (I don't remember which it was) offers it as prename.

  • Is there any still-supported distribution that offers it as rename but not as prename? In Debian rename has been a symlink to prename since 2008. Sep 5, 2017 at 22:37

This could be done with mv:

for name in ./foo*; do mv "$name" "${name/foo/foo-bar}"; done

For example:

[devuser@machine test]$ touch foo.log foo.pdf foo.tex foo.py
[devuser@machine test]$ ls
foo.log  foo.pdf  foo.py  foo.tex
[devuser@machine test]$ for name in ./foo*; do mv "$name" "${name/foo/foo-bar}"; done
[devuser@machine test]$ ls
foo-bar.log  foo-bar.pdf  foo-bar.py  foo-bar.tex

You must log in to answer this question.

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