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. This is the rename
command provided by the perl
package on Debian and derivatives (Ubuntu, Mint, …), but not on other distributions which may have a different utility called rename
.
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...
if [ $f == $prefix* ]
and you can change the suffix one withif [ $f == *$suffix$([ ! -z $extension ] && echo -n '.')$extension ]
around the couple mv commands in addsuffix. For (2) it should already work on files with no extension, unless I am a horrible programmer. – Aaron Okano Sep 21 '13 at 00:30