2012-09-04 78 views
3

我想a)计算我的mass filer EMC设备上有多少个文件,b)将它们加载到数组中c)显示我有多少个文件的计数d)散装加载我的数据库中的每个文件e)显示我刚加载的文件的名称。无法显示数组中的目录内容

这是我的代码...

export OUT=/path/to/device 
P_Array=$(cd ${OUT} ; find . -name "*TXT" | wc -l) 
Plen=${#P_Array[@]} 
echo "$Plen FILES TO PROCESS."          
if [ $Plen -eq 0 ] 
then 
     echo "`date '+%m/%d/%y %T:'` ZERO FILES."     
fi 

for name in ${P_Array[@]} 
do 
     ###Database Bulk Load Here### 
     echo "`date '+%m/%d/%y %T:'` $name was loaded." 
done 

问题答:Plen=${#P_Array[@]}显示计数1时,它应该是5盒(sandbox ENV,现在)。 问题B:$name显示文件的总数而不是单个文件名。

显然,这是全部错误的。我相信我有一些转变,但我不知道它是什么。帮帮我!

回答

3

由于您对find的结果做了wc -l这会给出文件的数量。因此,P_Array只包含一个数字。所以Plen只是1

他们更改为:

P_Array=$(cd ${OUT} ; find . -name "*TXT") 
Plen=$(cd ${OUT} ; find . -name "*TXT" | wc -l) 
+0

好悲伤。发现得好。接受并投票决定。谢谢。 – Chris

1

你需要让P_Array一个实际的阵列,而不是字符串中的空格分隔的单词列表:

P_Array=($(cd ${OUT} ; find . -name "*TXT")) 
Plen=${#P_Array[@]} 

如果任何文件在文件名中有空格,这将不起作用,因为这样的文件将作为数组中部分文件名的序列结束。在这种情况下,你必须做一些像

pushd "$OUT"   # Switch to the desired directory 
P_array=(*TXT) 
popd     # Return to the previous directory, if you like. 
Plen=${#P_Array[@]} 

(实际上,这可能比在第一时间使用find一个更好的主意。)


如果你使用一个数组,你已经放弃了POSIX合规性,所以这里是你的脚本的其余部分,用更多bash-isms简化:

date_fmt='%m/%d/%y %T' 
if ((Plen = 0)) 
then 
    # $(...) is still POSIX, but is also preferred over backticks 
    # printf is also preferred, and you can transfer the formatting 
    # from date to the printf. 
    printf "%($date_fmt)T: ZERO FILES\n" $(date +%s) 
fi 

# Quote the array expansion, in case of space-containing filenames 
for name in "${P_Array[@]}" 
do 
    ###Database Bulk Load Here### 
    # (be sure to quote $name when doing the bulk load) 
    printf "%($date_fmt)T: $name was loaded\n" $(date +%s) 
done 
+0

正确。这是我一直在处理的另一个问题。有时,我们的供应商会感到活跃并向我们发送空间文件。 – Chris