我使用以下 Bash Shell 脚本递归列出当前目录下的“.txt”文件:
#!/bin/bash
for file in $( find . -type f -name "*.txt" )
do
echo $file
# Do something else.
done
但是,当前目录下的某些“.txt”文件的名称中有空格,例如“我的测试.txt”。该列表已损坏,例如“我的testing.txt”列为
my
testing.txt
似乎“for”循环使用“空格”(空格、\n 等)来分隔文件列表,但在我的例子中,我只想使用“\n”来分隔文件列表。
有什么办法可以修改这个脚本来实现这个目的。任何想法。
提前致谢。
最佳答案
如果您使用的是 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
一定要引用 "$file"
否则你会在其他地方遇到同样的问题。 **
将递归匹配文件和目录,如果您启用了 globstar
。
关于Bash Shell 使用 "for"循环列出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9139214/