2

I have many files like xyz_123_foo.ext for which I would like to add -bar to the filenames at the end to result in xyz_123_foo-bar.ext. I tried:

rename . -bar. xyz_*

which resulted in:

rename: invalid option -- 'b'

followed by the usage text. I then tried variations with '-bar' and "-bar" to no avail.

How can I get rename to accept - as part of the replacement string?
Or would another command be more efficient or appropriate?

My shell is bash and I am using the rename from util-linux on SuSe Linux SLE12.

4

mmv is nice for tasks like this ex.

mmv -n -- '*.ext' '#1-bar.ext'

or for any dot extension

mmv -n -- '*.*' '#1-bar.#2'

Remove the -n once you are happy that it is doing the right thing.

  • This seems really elegant, but I get an error and the usage when I use the -n Option: > mmv -n '*.*' '#1-bar.#2' .../mmv: illegal option -- n .../mmv: [ -b ] [ -f Files ] [ -s Source ] [ -t Target ] Without -n nothing seems to happen – astzge2 Nov 28 '18 at 16:00
  • @astzge2 it seems our mmvs are different unfortunately - what is your OS? – steeldriver Nov 28 '18 at 16:07
  • I'm on SLE12. However, you've inadvertently answered my question! The -- end-of-options in Linux was unknown to me until I saw your edit. Including that caused rename to stop interpreting -bar. as a -b option. Thanks! – astzge2 Nov 29 '18 at 8:01
3

Assuming that your rename is the Perl variant of the rename utility:

rename 's/$/-bak/' xyz_*

This uses a Perl expression that simply inserts -bak at the end of all given filenames through a substitution of $ (the "end of line" anchor).

You could also use

rename '$_ .= "-bak"' xyz_*

which uses another Perl expression that appends the string -bak to $_ (the "current thing" in Perl, here it's a filename).

For a shell loop solution:

for name in xyz_*; do
    mv -i "$name" "$name-bak"
done
  • The Perl rename won't help if they have the util-linux one... – ilkkachu Nov 28 '18 at 15:41
  • @ilkkachu Added short note about that. That's also why I complemented the answer with a standard shell loop. – Kusalananda Nov 28 '18 at 16:01
1

Assuming we're talking about the PERL extension, rename (and not the rename from util-linux)...

rename 's/.ext/-bar.ext/' xyz_123_foo.ext

The result changes the file name to xyz_123_foo-bar.ext.

The portion within single quotes is a PERL regular expression. The s substitutes .ext in the file name with -bar.ext. One might combine this with find, assuming these files are in your home directory (~).

find ~ -type f -name '*.ext' -exec rename 's/.ext/-bar.ext/' {} +

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.