Bash – renaming mp3 files starting with “-”

bashfilesrename

I've extracted songs from my ipod, but when doing so, every song was renamed "- [original name of the song]" . I wanted to write a bash script that would remove that first "-" because there are maybe a 1000 songs in there and I can't rename each of them manually. I've tried to do it using mv and rename but it won't work because of the special characters. I've looked it up on the internet and I found a solution that consists in replacing "-" with "" but the problem is that I want to remove only the first "-" and not the potential others that can be in my song's name.
I hope I was clear enough and that someone can help me?

Here is my original script :

#!/bin/bash
for f in *; do
  echo "${f}";
  if [[ ${f:0:1} == "-" ]]; then
    echo "renaming ${f}";   
    rename.ul ${f} ${f:1} *.mp3;
fi
done

Best Answer

for f in -*.mp3; do
  echo mv -- "$f" "${f:1}"
done

When you are sure that it does what you want it to do, remove the echo.

The double dash (--) is necessary to stop mv from interpreting the - in the filenames as an option. Quoting the variables is necessary for the cases where the filenames contains spaces.

Related Question