使用shell脚本将文件名存储在数组中

时间:2014-02-22 08:19:11

标签: bash shell

#!/bin/bash

for m in `ls f-*`
do
$i = 0
echo "$m"
arr[$i] = $m
$i = $i + 1
done

我想在数组中存储以f-开头的文件名。上面的代码不起作用。

  

已编辑:

#!/bin/bash

i=0
ls f-* | while read m
do
#echo $m
arr[$i]=$m
i=$((i+1))
done

我收到以下错误,

my_script.sh: 7: my_script.sh: arr[0]=f-1: not found
my_script.sh: 7: my_script.sh: arr[1]=f-10: not found
my_script.sh: 7: my_script.sh: arr[2]=f-15: not found
my_script.sh: 7: my_script.sh: arr[3]=f-2: not found
my_script.sh: 7: my_script.sh: arr[4]=f-20: not found
my_script.sh: 7: my_script.sh: arr[5]=f-3: not found
my_script.sh: 7: my_script.sh: arr[6]=f-4: not found
my_script.sh: 7: my_script.sh: arr[7]=f-5: not found
my_script.sh: 7: my_script.sh: arr[8]=f-6: not found
my_script.sh: 7: my_script.sh: arr[9]=f-7: not found
my_script.sh: 7: my_script.sh: arr[10]=f-8: not found
my_script.sh: 7: my_script.sh: arr[11]=f-9: not found

EDITED1:

#!/bin/bash

i=0
for i
do
#echo $m
arr[$i]= f-*i
echo $arr[i]
i=$((i+1))
done

3 个答案:

答案 0 :(得分:6)

您不需要循环。

arr=( f-* )

答案 1 :(得分:2)

Shell变量赋值在=周围不能有任何空格,并且您不会在分配变量之前放置$。您也不需要使用ls,只需将通配符放在for语句中。

i=0     # initialize the variable before the loop
for m in f-*
do
    echo "$m"
    arr[$i]=$m
    i=$((i + 1))
done

答案 2 :(得分:0)

这有帮助吗?

#!/bin/bash

echo ls: $(ls)
echo ""

seqmax=0
for file in $(ls ./f-* ); do
    char=$( echo $file | wc -c )
    if [ $char > $seqmax ];then
        seqmax=$char
    fi
done
i=0
for count in $(seq 1 1 $seqmax);do
    for file in $(ls | egrep "^f\-.{$count}$");do
        completearray[$i]=$file
        i=$(expr $i + 1 )
    done
done

echo ${completearray[@]}

这应打印如下。

$ ./script.sh
ls: f-1 f-15 f-16 f-2 f-3 f-one f-two g-1 g-2 g-3 script.sh

f-1 f-2 f-3 f-15 f-16 f-one f-two

如果你需要它只能获得"数字"不是所有字符都可以将for file in $(ls | egrep "^f\-.{$count}$");do更改为for file in $(ls | egrep "^f\-[0-9]{$count}$");do