Re: Bash: for…in-loop fails, what am I doing wrong?

Johnny Rosenberg gurus.knugum at gmail.com
Thu Jan 10 19:48:48 UTC 2013


2013/1/10 Johnny Rosenberg <gurus.knugum at gmail.com>:
> 2013/1/10 Johnny Rosenberg <gurus.knugum at gmail.com>:
>> Obviously I'm still a beginner at this. Here's a one-liner that
>> demonstrates my problem:
>>
>> for File in "$(find ${PWD} -regextype posix-extended -regex
>> '.*/P[A-Z0-9][0-9]{6}\.(jpg|JPG|jpeg)')"; do FileDate=$(date
>> --reference="${File}" '+%Y%m'); done
>>
>>
>> In a script, (easier to read…):
>> for File in "$(find ${PWD} -regextype posix-extended -regex
>> '.*/P[A-Z0-9][0-9]{6}\.(jpg|JPG|jpeg)')"
>
> It's those quotes that cause my problems, isn't it?
> But if I omit them, paths with spaces would go wrong, wouldn't they?
> So what now…? :(
>
> I could, of course, first do the find thing and redirect its output to
> a file and then loop the file line by line… but I am not sure that
> would help. I still have file paths with spaces in them… How to
> separate a list with newlines and NOT with spaces? I guess that's the
> tricky bit here…
>
> More input still appreciated…
>
>
> Johnny Rosenberg
>
> Johnny Rosenberg
>
>
>> do
>>     FileDate=$(date --reference="${File}" '+%Y%m')
>>     # More things to happen here, but this is only a test.
>> done
>>
>> The regex works, and it finds files with names starting with P, then
>> [A-Z0-9], then 6 numbers followed by .jpeg or .JPG or .jpg. Example:
>> PA123456.JPG
>> It finds them, that's not the problem.
>>
>> So what's the problem?
>> Here's a faked output (the original output is too long):
>>
>> ~$ for File in "$(find ${PWD} -regextype posix-extended -regex
>> '.*/P[A-Z0-9][0-9]{6}\.(jpg|JPG|jpeg)')"; do FileDate=`date
>> --reference="${File}" '+%Y%m'`; echo "${FileDate}"; done
>> date: /some/path/P1010077.jpeg
>> /some/other/path/P1010018.jpeg
>> /another/path/P1010023.jpeg
>> /yet/another/path/P0000729.jpeg: File or directory does not exist
>>
>> ~$
>>
>> Maybe I totally misunderstood the for loop thing, but it seems like
>> the date command is performed once for all paths at once, which is not
>> what I want. I thought of it as an ordinary for loop in C, for
>> instance, executing the date line once for each path name.
>>
>> What am I missing here? I'm probably just stupid, so I hope for your patience…
>>
>> Of course I have checked that those files exists; they are found by
>> the find command, so they MUST exist, right?
>>
>>
>> Johnny Rosenberg

I think I found all the information I need here:
http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html

Maybe it could be useful for someone else as well.


Johnny Rosenberg




More information about the ubuntu-users mailing list