Linux bash:将列表文件放入一个变量中,但数组的大小为 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15224535/
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: put list files into a variable and but size of array is 1
提问by Waygood
I am listing the files in a directory and looping through them okay, BUT I need to know how many there are too. ${#dirlist[@]} is always 1, but for loop works?
我在一个目录中列出文件并循环遍历它们,但我也需要知道有多少。${#dirlist[@]} 总是 1,但是 for 循环有效吗?
#!/bin/bash
prefix="xxx"; # as example
len=${#prefix}; # string length
dirlist=`ls ${prefix}*.text`;
qty=${#dirlist[@]}; # sizeof array is always 1
for filelist in $dirlist
do
substring="${filelist:$len:-5}";
echo "${substring}/${qty}";
done
I have files xxx001.text upto xxx013.text
but all I get is 001/1 002/1 003/1
我有文件 xxx001.text 到 xxx013.text
但我得到的只是 001/1 002/1 003/1
采纳答案by KarelSk
This:
这个:
dirlist=`ls ${prefix}*.text`
doesn't make an array. It only makes a string with space separated file names.
不做数组。它只生成一个以空格分隔的文件名的字符串。
You have to do
你必须要做
dirlist=(`ls ${prefix}*.text`)
to make it an array.
使它成为一个数组。
Then $dirlist
will reference only the first element, so you have to use
然后$dirlist
将仅引用第一个元素,因此您必须使用
${dirlist[*]}
to reference all of them in the loop.
在循环中引用所有这些。
回答by Costi Ciudatu
You're not creating an array unless you surround it with (
)
:
除非您用(
)
以下内容包围它,否则您不会创建数组:
dirlist=(`ls ${prefix}*.text`)
回答by Mikhail Vladimirov
dir=/tmp
file_count=`ls -B "$dir" | wc -l`
echo File count: $file_count
回答by dilshad
arr=(~/myDir/*)
iterate through array using a counter
使用计数器遍历数组
for ((i=0; i<${#arr[@]}; i++)); do
#do something to each element of array
echo "${arr[$i]}"
done