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

Re: Handle paths with spaces



In <[🔎] 4B460D6C.3050007@symantec.com>, Bob McGowan wrote:
>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:

Yes, that's why he mentioned the -0 option to xargs.  If you are using -print0 
with find, you'll probably want to pipe in into xargs -0.

(find -type f -print0 | xargs -0 -- grep -i foo --) for example.

>>> Script:
>>>
>>> for file in `find -name "*.txt"`
>>> do
>>>     echo file: $file
>>> done
>>
>> You need to quote $file here:
>>      echo file: "$file"
>
>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.

The "read" builtin handles spaces as normal characters, but it can mishandle 
other characters like '\'.  '-print0' piped into 'xargs -0' is fairly 
foolproof, but not available everywhere.  Having find run a shell script via 
exec should work everywhere, and handles any character the platform support in 
a filename.
-- 
Boyd Stephen Smith Jr.                   ,= ,-_-. =.
bss@iguanasuicide.net                   ((_/)o o(\_))
ICQ: 514984 YM/AIM: DaTwinkDaddy         `-'(. .)`-'
http://iguanasuicide.net/                    \_/

Attachment: signature.asc
Description: This is a digitally signed message part.


Reply to: