Balpo
Balpo

Reputation: 13

awk/sed join all lines and pass it to another program

I have a script that picks for me N random files from a directory and I need the output to be passed as an argument for amarok or vlc.

My script pick.sh is:

#!/usr/bin/env bash
find "$1" -name *mp3 | shuf -n "$2" | sed -r 's/(.*)/"&"/' | awk 'NR%10{printf $0" ";next;}1'#it should be $2 instead of 10

So to randomly select 3 files on my music directory I do:

pick.sh /music/ 3

and the script returns 3 songs surrounded by double quotes (because they may contain spaces) all in one line:

"/music/s/Los Straitjackets/!Viva!/Los Straitjackets - Outta Gear.mp3" "/music/p/Plastilina Mosh/Juan Manuel/Plastilina Mosh - Graceland.mp3" "/music/s/Snoop Dogg/R&G (Rhythm & Gangsta); The Masterpiece/Snoop Dogg - No Thang On Me.mp3"

But I want to directly pass the results of pick.sh to vlc:

vlc "$(pick.sh /music/ 3)" &

but it adds each token separated by spaces.

However, if I copy the output of pick.sh and then paste it after calling vlc, all goes ok.

How can I make vlc (or amarok or whatever program) to correctly parse pick.sh's output?

Thank you for your help!

Upvotes: 0

Views: 78

Answers (1)

user3159253
user3159253

Reputation: 17455

It's better not to quote filenames manually because names can contain quotes as well, so you should properly escape them.

One may write the filenames one by one, with each filename on its own line and then use xargs program to feed vlc with arguments:

 find "$1" -name '*.mp3' -print | shuf -n "$2" | xargs vlc

Admittedly, if your music collection contains files with '\n' (newline) in its name (well, unlikely, but it could :) ), then you have to cope with the case, and use '\0' as a record separator on each stage of processing:

find "$1" -name '*.mp3' -print0 | shuf -z -n "$2" | xargs -0 vlc

but usually it's an overkill.

Also it should be mentioned that in unix like shells, unlike Microsoft Windows approach, programs do not parse their command line arguments because the latter are passed to programs in separated form. All splittings by whitespaces, handling quotings etc are performed by a calling side, usually a shell. This explains why vlc runs correctly when you simply copy a given line to shell and run it "manually".

Upvotes: 1

Related Questions