Make xargs handle filenames that contain spaces

前端 未结 12 1164
北恋
北恋 2020-11-29 15:21
$ ls *mp3 | xargs mplayer  

Playing Lemon.  
File not found: \'Lemon\'  
Playing Tree.mp3.  
File not found: \'Tree.mp3\'  

Exiting... (End of file)  
12条回答
  •  旧巷少年郎
    2020-11-29 15:30

    It depends on (a) how attached you are to the number 7 as opposed to, say, Lemons, and (b) whether any of your file names contain newlines (and whether you're willing to rename them if they do).

    There are many ways to deal with it, but some of them are:

    mplayer Lemon*.mp3
    
    find . -name 'Lemon*.mp3' -exec mplayer {} ';'
    
    i=0
    for mp3 in *.mp3
    do
        i=$((i+1))
        [ $i = 7 ] && mplayer "$mp3"
    done
    
    for mp3 in *.mp3
    do
        case "$mp3" in
        (Lemon*) mplayer "$mp3";;
        esac
    done
    
    i=0
    find . -name *.mp3 |
    while read mp3
    do
        i=$((i+1))
        [ $i = 7 ] && mplayer "$mp3"
    done
    

    The read loop doesn't work if file names contain newlines; the others work correctly even with newlines in the names (let alone spaces). For my money, if you have file names containing a newline, you should rename the file without the newline. Using the double quotes around the file name is key to the loops working correctly.

    If you have GNU find and GNU xargs (or FreeBSD (*BSD?), or Mac OS X), you can also use the -print0 and -0 options, as in:

    find . -name 'Lemon*.mp3' -print0 | xargs -0 mplayer
    

    This works regardless of the contents of the name (the only two characters that cannot appear in a file name are slash and NUL, and the slash causes no problems in a file path, so using NUL as the name delimiter covers everything). However, if you need to filter out the first 6 entries, you need a program that handles 'lines' ended by NUL instead of newline...and I'm not sure there are any.

    The first is by far the simplest for the specific case on hand; however, it may not generalize to cover your other scenarios that you've not yet listed.

提交回复
热议问题