Skip to main content
1 of 3
Martin von Wittich
  • 14.7k
  • 6
  • 56
  • 77

There's a Perl rename command that should do the trick (beware though: there are several different commands called rename, so make sure you have got the Perl script that expects a perlexpr as its argument):

martin@martin ~/test % touch a.txt
martin@martin ~/test % touch b.txt
martin@martin ~/test % rename 's/^(prefix)?/prefix/' *.txt
martin@martin ~/test % ll
insgesamt 0
-rw-rw-r-- 1 martin martin 0 Sep 19 23:56 prefixa.txt
-rw-rw-r-- 1 martin martin 0 Sep 19 23:56 prefixb.txt
martin@martin ~/test % rename 's/^(prefix)?/prefix/' *.txt
martin@martin ~/test % ll
insgesamt 0
-rw-rw-r-- 1 martin martin 0 Sep 19 23:56 prefixa.txt
-rw-rw-r-- 1 martin martin 0 Sep 19 23:56 prefixb.txt

As you can see, it's idempotent - it won't add the prefix again when you call it multiple times.

It works by either replacing the (zero-length) start of the strings (^) or the start followed by an optional prefix string with prefix.

I'll leave encapsulating this in either a shell script or a shell function as an exercise for you :)

Postfix is a bit harder though, because you have to figure out what part of the filename constitutes the extension...

Martin von Wittich
  • 14.7k
  • 6
  • 56
  • 77