Wednesday, 2 June 2010

Fun with find

I found (ha) myself with a sticky problem. I had a directory tree of mp3 files that I wanted to play in directory order and filename order within the directories. From the outset, it seemed a trivial enough problem: use find and exec and off you go.

Except some of the files had spaces in them, meaning that I had to use the -print0 arg which then meant that I had to wrap the output in quotes, replace the NULL char with a \n char before I could finally pass it on to sort and xargs.

After much scratching of head, I came up with this:find -type f -print0 | xargs -0 printf "\"%s\"\n"| sort
"./01/01 Track.mp3"
"./01/02 Track.mp3"
"./01/03 Track.mp3"
"./01/04 Track.mp3"
"./01/05 Track.mp3"
"./01/06 Track.mp3"
"./01/07 Track.mp3"
"./01/09 Track.mp3"
"./02/01 Track.mp3"
:
etc


Which sorts by directory and file. Simply pipe to what ever it is you want do with it. Eg:


find -type f -print0 | xargs -0 printf "\"%s\"\n"| sort | xargs mplayer

Further reading on similar issues and different approaches can be found here on the unixjunkie blog.

man find, man xargs and man printf are also your friend.

No comments: