Search code examples
bashls

What can I do with new lines in file name?


If a file has new line symbol in it, and I use find or ls, it shows as "?" symbol in a file name. But when I use | to do anything more with it, it splits the string and messes up everything. How do I deal with it?


Solution

  • Don't pipe the results of ls at all. It is, as you see, unpredictable. Use find instead:

    find -maxdepth 1 -exec command {} \;
    

    {} represents the file name.

    Alternatively you can also use glob expressions. The results of a glob expression are not subject of word splitting, meaning it is safe if they contain newlines or spaces:

    for file in ./* ; do
        command "$file"
    done
    

    The results of that commands can then be used in another pipe.