Step away from ls if at all possible. Use find from the findutils package.
find /target/path -type f -print0 | xargs -0 your_command_here
-print0
will cause find to output the names separated by NUL characters (ASCII zero). The -0
argument to xargs tells it to expect the arguments separated by NUL characters too, so everything will work just fine.
Replace /target/path
with the path under which your files are located.
-type f
will only locate files. Use -type d
for directories, or omit altogether to get both.
Replace your_command_here
with the command you'll use to process the file names. (Note: If you run this from a shell using echo for your_command_here you'll get everything on one line - don't get confused by that shell artifact, xargs will do the expected right thing anyway.)
Edit: Alternatively (or if you don't have xargs), you can use the much less efficient
find /target/path -type f -exec your_command_here \{\} \;
\{\} \;
is the escape for {} ;
which is the placeholder for the currently processed file. find will then invoke your_command_here
with {} ;
replaced by the file name, and since your_command_here
will be launched by find and not by the shell the spaces won't matter.
The second version will be less efficient since find will launch a new process for each and every file found. xargs is smart enough to pipe the commands to a newly launched process if it can figure it's safe to do so. Prefer the xargs version if you have the choice.