简体   繁体   English

bash:将列表文件放入一个变量中,但数组的大小为 1

[英]bash: put list files into a variable and but size of array is 1

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我有文件 xxx001.text 到 xxx013.text
but all I get is 001/1 002/1 003/1但我得到的只是 001/1 002/1 003/1

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.在循环中引用所有这些。

除非用( )包围它,否则您不会创建数组:

dirlist=(`ls ${prefix}*.text`)
dir=/tmp
file_count=`ls -B "$dir" | wc -l`
echo File count: $file_count

Declare an array of files:声明一个文件数组:

arr=(~/myDir/*)

Iterate through the array using a counter:使用计数器遍历数组:

for ((i=0; i < ${#arr[@]}; i++)); do

  # [do something to each element of array]

  echo "${arr[$i]}"
done

The array syntax in bash is simple, using parentheses ( and ) : bash数组语法很简单,使用括号()

# string
var=name

# NOT array of 3 elements
# delimiter is space ' ' not ,
arr=(one,two,three) 
echo ${#arr[@]}
1

# with space
arr=(one two three)
# or ' ',
arr=(one, two, three)
echo ${#arr[@]}
3

# brace expansion works as well
# 10 elements
arr=({0..9})
echo ${#arr[@]}
10

# advanced one
curly_flags=(--{ftp,ssl,dns,http,email,fc,fmp,fr,fl,dc,domain,help});
echo ${curly_flags[@]}
--ftp --ssl --dns --http --email --fc --fmp --fr --fl --dc --domain --help
echo ${#curly_flags[@]}
12

if you want to run a command and store the output如果要运行命令并存储输出

# a string of output
arr=$(ls)
echo ${#arr[@]}
1

# wrapping with parentheses
arr=($(ls))
echo ${#arr[@]}
256

A more advanced / handy way is by using built-in bash commands mapfile or readarray and process substitution .更高级/更方便的方法是使用内置的bash 命令mapfilereadarray进程替换 here is is an example of using mapfile :这是使用mapfile的示例:

# read the output of ls, save it in the array name: my_arr
# -t    Remove a trailing DELIM from each line read (default newline)
mapfile -t my_arr < <(ls)
echo ${#my_arr[@]}
256

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM