ffmpeg - Splitting up a variable in bash -
i have bunch of songs have downloaded trying convert .mp3 , rename. after converting .m4a file mp3 ffmpeg
, in format of artist name - song name.mp3. want able separate song name , artist name own variables, can rename file , tag songs song name , artist name.
so, how can separate variable 2 variables, each respectively containing artist name , song name, 2 pieces of information separated ' - ' in bash?
using shell
v='artist name - song name.mp3' v=${v%.mp3} song=${v#* - } artist=${v% - $song} echo a=$artist, s=$song
this produces output:
a=artist name, s=song name
notice approach, sed solution below, consistently divides artist , song @ first occurrence of -
. thus, if name is:
v='artist name - song name - 2nd take.mp3'
then, output is:
a=artist name, s=song name - 2nd take
this approach posix , works under dash
, busybox
under bash
.
using sed
$ v='artist name - song name.mp3' $ { read -r artist; read -r song; } < <(sed 's/.mp3$//; s/ - /\n/' <<<"$v") $ echo a=$artist s=$song a=artist name s=song name
this assumes (1) first occurrence of -
divides artist name song name, , (2) file name, $v
, has line (no newline characters).
we can overcome second limitation using, if tools support it, nul separator instead of newline:
$ { read -r -d $'\0' artist; read -r -d $'\0' song; } < <(sed 's/.mp3$//; s/ - /\x00/' <<<"$v"); echo a=$artist s=$song a=artist name s=song name
here example newline characters inside both artist , song names:
$ v=$'artist\nname - song\nname.mp3' $ { read -r -d $'\0' artist; read -r -d $'\0' song; } < <(sed 's/.mp3$//; s/ - /\x00/' <<<"$v"); echo "a=$artist"; echo "s=$song" a=artist name s=song name
how works
the sed command removes .mp3
suffix , replaces -
newline character:
sed 's/.mp3$//; s/ - /\n/' <<<"$v"
the output of sed command consists of 2 lines. first line has artist name , second song name. these read 2 read
commands.
Comments
Post a Comment