Bash Shell 使用“for”循环列出文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9139214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash Shell list files using "for" loop
提问by user1129812
I use the following Bash Shell script to list the ".txt" files recursively under the current directory :
我使用以下 Bash Shell 脚本递归列出当前目录下的“.txt”文件:
#!/bin/bash
for file in $( find . -type f -name "*.txt" )
do
echo $file
# Do something else.
done
However, some of the ".txt" files under the current directory have spaces in their names, e.g. "my testing.txt". The listing becomes corrupted, e.g. "my testing.txt" is listed as
但是,当前目录下的一些“.txt”文件的名称中有空格,例如“my testing.txt”。列表已损坏,例如“my testing.txt”被列为
my
testing.txt
It seems that the "for" loop uses "white space" (space, \n etc) to separate the file list but in my case I want to use only "\n" to separate the file list.
似乎“for”循环使用“空白”(空格、\n 等)来分隔文件列表,但在我的情况下,我只想使用“\n”来分隔文件列表。
Is there any way I could modify this script to achieve this purpose. Any idea.
有什么办法可以修改这个脚本来达到这个目的。任何的想法。
Thanks in advance.
提前致谢。
采纳答案by FatalError
If you're using bash 4, just use a glob:
如果您使用的是 bash 4,只需使用 glob:
#!/bin/bash
shopt -s globstar
for file in **/*.txt
do
if [[ ! -f "$file" ]]
then
continue
fi
echo "$file"
# Do something else.
done
Be sure to quote "$file"or you'll have the same problem elsewhere. **will recursively match files and directories if you have enabled globstar.
一定要引用,"$file"否则你会在其他地方遇到同样的问题。**如果您启用了globstar.
回答by SiegeX
Yes, have findseparate the file names with NUL and use readto delimit on NUL. This will successfully iterate over any file name since NUL is not a valid character for a file name.
是的,find将文件名与 NUL 分开并用于read分隔NUL. 这将成功迭代任何文件名,因为 NUL 不是文件名的有效字符。
#!/bin/bash
while IFS= read -r -d '' file; do
echo "$file"
# Do something else.
done < <(find . -type f -name "*.txt" -print0)
Alternatively, if the # do something elseis not too complex, you can use find's -execoption and not have to worry about proper delimiting
或者,如果# do something else不是太复杂,您可以使用find's-exec选项而不必担心正确的分隔

