Shell – Rename files in the local folder adding a prefix or suffix

renameshellshell-script

I have many files in a folder and I want to add either prefix or a suffix (not both) to them. I checked here and found out I can use

for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;

to add a prefix to all files ending in .jpg (and if I remove the .jpg, it will add the prefix to all the files in the current folder).

However, I'd like to be able to

  • Add a sufix (that is, rename filename.ext to filename.whatever.ext),
  • Check if the prefix or suffix is already present and then skip,
  • Create an alias that accepts arguments such as addprefix whatever *.ext or addsufix whatever *.*

Best Answer

If you're using bash, then this one-liner can do it for you (assuming you have the variables $prefix, $suffix and $extension readily available)

mv "$filename" "$prefix${filename%.$extension}$suffix.$extension"

You could have your scripts be like this

#!/bin/bash
# Usage: addprefix <prefix> <files>

prefix=$1
shift
for f in "$@"
do
  mv "$f" "$prefix$f"
done

and

#!/bin/bash
# addsuffix <suffix> <files>

suffix=$1
shift
for f in "$@"
do
  extension=${f##*.}
  if [ -z $extension ]; then
    mv "$f" "$f$suffix"
  else
    mv "$f" "${f%.$extension}$suffix.$extension"
  fi
done
Related Question