I have a bunch of songs that I have downloaded that I am trying to convert to .mp3 and rename. After converting the .m4a file to mp3 with ffmpeg
, they are all in the format of Artist Name - Song Name.mp3. I want to be able to separate the Song name and Artist name into their own variables, so I can rename the file and tag the songs with the song name and artist name.
So, How can I separate a variable into two variables, each respectively containing the artist name and song name, where the two pieces of information is separated by a ' - ' in bash?
Using shell
This produces the output:
Notice that this approach, like the sed solution below, consistently divides the artist and song at the first occurrence of
-
. Thus, if the name is:Then, the output is:
This approach is POSIX and works under
dash
andbusybox
as well as underbash
.Using sed
This assumes (1) the first occurrence of
-
divides the artist name from the song name, and (2) the file name,$v
, has only line (no newline characters).We can overcome the second limitation by using, if your tools support it, NUL as the separator instead of newline:
Here is an example with newline characters inside both the artist and song names:
How it works
The sed command removes the
.mp3
suffix and then replaces-
with a newline character:The output of the sed command consists of two lines. The first line has the artist name and the second the song name. These are then read by the two
read
commands.