我想在阵列把结果命令find *.txt
,然后遍历数组了这样申报阵列find命令的结果
for file in array
do
done
我需要把数组,因为以后我需要访问到阵列。所以解决方案
for file in `find *.txt`
do
done
对我不好。
我想在阵列把结果命令find *.txt
,然后遍历数组了这样申报阵列find命令的结果
for file in array
do
done
我需要把数组,因为以后我需要访问到阵列。所以解决方案
for file in `find *.txt`
do
done
对我不好。
使用数组赋值语法:
array=($(find *.txt))
如果可以有空格的文件名,你应该把
IFS=$"\n"
上面的命令。如果文件名中可能有换行符,它会变得非常复杂,我不知道处理它的好方法。
然后你可以迭代它具有:
for file in "${array[@]}"
让我们希望文件名中没有空格......希望和祈祷!你胆大妄为! –
如果你确定你没有任何的换行符在你的文件名,mapfile
是一个不错的选择:
mapfile -t array < <(find . -name '*.txt')
现在,如果你想要更多的东西防弹,你可以使用:
mapfile -t array < <(find . -name '*.txt' -exec bash -c 'printf "%q\n" "${@:0}"' {} +)
eval array=(${array[@]})
看到最后一行:eval
和未加引号${array[@]}
,您应该感觉非常糟糕。它的工作原理是防弹的,因为array
是使用printf
的'%q'修饰符构建的,所以一切都很好地转义或引用,以便在这里安全使用!
对于'printf'%q \ n“'的很好的使用+1 – John1024
其他答案都有美德。作为一种补充,在这里是一种方法,其中(a)是即使在最困难的文件名安全,(二)允许充分利用find
的力量,以及(c)避免eval
:
array=()
while read -r -d $'\0'; do
array+=("$REPLY")
done < <(find . -name '*.txt' -print0)
你为什么使用'find'? 'find * .txt'和'* .txt'之间没有区别,除非你有名称以'.txt'结尾的子目录。你的意思是'发现。 -name'* .txt''? – Barmar