3

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
4
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.

  • 1
    It works perfectly, thank you so much !!! The errors were actually telling me that, but I didn't get it until a saw your answer. Thanks again ;) – Kashouf Jul 14 '16 at 16:57
  • @Kashouf If that solves your issue, please consider accepting the answer. – Kusalananda Jul 14 '16 at 20:29
1

When you pass an argument beginning with a dash to a command, and you don't want this argument to be interpreted as an option, pass -- (double dash) as an argument first. With almost all commands, -- means “no more options after this”.

rename.ul -- '-' '' -*

Another possibility is to arrange for the argument not to start with a dash. This isn't always possible, but for a file name, it is: add ./ in front.

rename.ul ./- ./ ./-*

Note that you don't need a loop — rename is happy with a list of files as arguments. Also you don't need to pass the whole file name, just the portion you want to rename. (In fact one of the problems with your script is that you're mixing things up, passing the whole file name as a string to replace but then passing a list of all files each time.)

Also always put double quotes around variable substitutions, otherwise your script won't work with file names containing spaces.

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.