[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Handle paths with spaces



Jon Dowland wrote:
> On Thu, Jan 07, 2010 at 03:38:23PM +0530, Foss User wrote:
>> I want to do some operation on each file ending with .txt. However,
>> this script wouldn't work because in each iteration it gets one word
>> from the output of find.
> 
> Did you read my reply to your last question?
> <http://lists.debian.org/debian-user/2010/01/msg00403.html>
> 
> Look at the -print0 arg for find and the -0 argument for
> xargs.

Doesn't work - bash and the 'for' loop work on newline terminated
strings and don't know how to handle the null terminator from -print0:

    $ find . -name '*txt'
    ./a b/tst.txt
    ./c/tst2.txt

    $ for n in $(find . -name '*txt')
    > do
    > echo $n
    > done
    ./a
    b/tst.txt
    ./c/tst2.txt

    $ for n in $(find . -name '*txt' -print0)
    > do
    > echo $n
    > done
    ./a
    b/tst.txt
    $

In the third 'find' command with -print0, only one file is found, and it
is still split on the space.

> 
>> Script:
>>
>> for file in `find -name "*.txt"`
>> do
>>     echo file: $file
>> done
> 
> You need to quote $file here:
>      echo file: "$file"
> 
> As described in another reply to your last thread,
> <http://lists.debian.org/debian-user/2010/01/msg00267.html>
> 
> Please ensure you carefully read the replies people have
> already written.
> 
> 

Generally a good idea to quote the variable, but in this case it won't
help, the split on spaces has happened before the arguments get to the
'echo'.

I would suggest to the OP that they use a 'while' loop rather than 'for':

    find . -name '*txt' |
    while read n
    do
      echo "$n"
    done
    ./a b/tst.txt
    ./c/tst2.txt

The 'read' gets the whole line, ignoring spaces.

-- 
Bob McGowan


Reply to: