如何在 FreeBSD /bin/sh 中迭代包含 space 的文件

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

我正在尝试使用 FreeBSD /bin/sh shell:

驱动一组包含 space 的文件
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

虽然我想得到:

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

遇到这种情况space应该怎么处理?

您需要将 IFS 设置为不包含 space 字符的值。

例如:

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

详情见manual page

有些人会为"the canonical Unix way of doing these kinds of things"

而努力奋斗
find . -type f | grep '03-11' | xargs -I {} echo {}