How can I handle a list of files containing spaces in their names on Unix?

I am trying to list files in a directory and do something for them at the Mac OS X prompt.

It should look like this: for f in $ (ls -1); do echo $ f; done

If I have files without spaces in their names (fileA.txt, fileB.txt), the echo works fine. If the files contain spaces in their names ("A.txt file", "B.txt file"), I get 4 lines (file, A.txt, file, B.txt).

I tried using the enumeration command, but that only changed the problem.

If I do this: for f in $ (ls -1); do echo $ f; done I get: file A.txt \ nfile B.txt

(It displays correctly, but it is one line, and I need two lines.

+3
source share
6 answers

Keep up with ls, if at all possible. Use find from findutils package.

find /target/path -type f -print0 | xargs -0 your_command_here

-print0will force find to output names separated by NUL characters (ASCII zero). The argument -0for xargs suggests that it expects arguments separated by NUL characters, so everything will work fine.

Replace /target/pathwith the path where your files are.

-type fwill only detect files. Use -type dfor directories or omit completely to get both.

your_command_here , . (. , echo _, - , xargs .)

: ( xargs),

find /target/path -type f -exec your_command_here \{\} \;

\{\} \; - escape {} ;, . find your_command_here {} ; , your_command_here find, , .

, find . xargs , , . xargs, .

+12
for f in *; do echo "$f"; done

, . ls *?

- PITA. $IFS Perl, Ruby, Python ..

+9

read. , cat :

ls -1 | while read FILENAME; do cat "$FILENAME"; done

, ls, , , $IFS .

while , . :

ls -1 | while read FILE
do
    echo 1: "$FILE"
    echo 2: "$FILE"
done
0

-quoting-style. , --quoting-style = c :

$ls --quoting-style = c

"file1" "file2" "dir one"

0

man- xargs:

:

ls -1/tmp/*.jpeg | xargs rm

-1

All Articles