How to iterate over files containing space in FreeBSD /bin/sh

Viewed 98

I am trying to actuate over a set of files that contain space using FreeBSD /bin/sh shell:

user@host:~/temp/2011 $ find . | grep '03-11'
./01jan/ES 03-11.txt
./02feb/ES 03-11.txt
./03mar/ES 03-11.txt
./04apr/ES 03-11.txt
./05may/ES 03-11.txt
user@host:~/temp/2011 $ for i in `find . | grep '03-11'`; do echo "$i"; done
./01jan/ES
03-11.txt
./02feb/ES
03-11.txt
./03mar/ES
03-11.txt
./04apr/ES
03-11.txt
./05may/ES
03-11.txt

While I would like to get:

user@host:~/temp/2011 $ find . | grep '03-11'
./01jan/ES 03-11.txt
./02feb/ES 03-11.txt
./03mar/ES 03-11.txt
./04apr/ES 03-11.txt
./05may/ES 03-11.txt
user@host:~/temp/2011 $ for i in `find . | grep '03-11'`; do echo "$i"; done
./01jan/ES 03-11.txt
./02feb/ES 03-11.txt
./03mar/ES 03-11.txt
./04apr/ES 03-11.txt
./05may/ES 03-11.txt

What shall be done to deal with the space in this case?

2 Answers

You need to set IFS to a value that does not include a space character.

For example:

(IFS=$'\n'; for i in `find . | grep '03-11'`; do echo "$i"; done)

See the manual page for details.

Related