qwerty_in_me
qwerty_in_me

Reputation: 1

delimit filenames containing spaces in shell scrip to pass to other programs

I have a music folder and the files are named by song title. I want to move songs of one artist to a folder named after said artist like so

Music
|Apache
| \Feeling Good.mp3
|
|Marian Hill
| \Down.mp3
|
\Kaito Shoma
  |GAZ.mp3
  \Scary Garry.mp3

as currently all the mp3s are in a single folder. The problem is: the files don't have the artist in them so I've got a script that iterates over all of them and returns a list of all files made by the same artist

#!/bin/sh
for file in *.mp3; do
    artist=$(ffprobe -hide_banner -of default=noprint_wrappers=1 -show_entries format -i "$file" 2>&1 | grep TAG:artist | sed s/TAG:artist=/ /);
    if [ "$1" != '' ]; then
        test "$artist" = "$1" && list=$list' '$file
    else
        list=$list' '$file
    fi
done
echo $list

now if I run it with mv $(script "artist") artist any filenames containing spaces don't get processed right and I end up with multiple lines of 'no such file' printf doesn't fare better or my name is just Chef BoyJuaredumb

I tried to replace $list' '$file with $list' '\"$file\" or $list'\n\"$file\" and some others to no avail either I'd get one line of

no such file: "str ing"

no such file: str
no such file: ing

or worse; both

I'm currently reading posix regex specifications for something I can use. I've got bash 5.1 and mksh 59.c-1 (acording to pacman)

I really don't want to use mv in the script partially because I'm not good at parsing parameters and want to use it to list the artists of all songs in directory (requires work) and partially because I don't know how to implement flags like -m/--move or -h/--help

Upvotes: 0

Views: 32

Answers (1)

Barmar
Barmar

Reputation: 781716

You can't do it with all the filenames in a single string, because quotes aren't processed when expanding a command substitution. Output the filenames on separate lines:

#!/bin/sh
for file in *.mp3; do
    artist=$(ffprobe -hide_banner -of default=noprint_wrappers=1 -show_entries format -i "$file" 2>&1 | sed -n 's/TAG:artist=//p');
    if [ "$1" != '' ]; then
        test "$artist" = "$1" && echo "$file"
    else
        echo "$file"
    fi
done

Then you can loop over that with a while read loop.

script "artist" | while read -r filename; do
    mv "$filename" "artist"
done

Upvotes: 1

Related Questions