1

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

~/mydir/foo.py
~/mydir/foo.tex
~/mydir/foo.pdf
~/mydir/foo.log

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

~/mydir/foo-bar.py
~/mydir/foo-bar.tex
~/mydir/foo-bar.pdf
~/mydir/foo-bar.log

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

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. – Gilles Sep 5 '17 at 22:37
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.