bash在变量名中使用for循环索引并将空值替换为0

问题描述

我有 1000 个文件夹,从 0000/ 到 0999/。每个文件夹都有一个特定的同名子文件夹。那是我的目标文件夹。目标文件夹有许多文本文件

我希望执行的是:

  1. 对于 1000 个文件夹,检查特定子文件夹的多个特定文本文件,以查看目标文件是否包含两个特定字符。
  2. 计算特定文本文件中的文件数,文件中有两个特定字符串 AAAAA 和 BBBBB。 (我为此使用了 grep)
  3. 有些文件夹甚至不包含某些文件夹。在这种情况下,输入 0。
  4. 打印出包含文件夹位置的号码。

这就是我现在使用两个 for 循环编写的内容。我还在脚本的每一行上方添加了我想做什么的注释:

#!/bin/bash

NUMDIR=1000   # number of folders from 0000 to 0999
NUM=2

# First for loop,index i
for i in $(seq -f %04g 0 $((NUMDIR-1))); do

     # Create new variable ii that removes 0 from index i,# just in case 0 preceding to the number in $i can cause a problem.
     ii=`echo $i | sed 's/^0*//'`

     # Second for loop,index j
     for j in $(seq 4 2 26); do

        # Declare the dynamic valriable using ii and j.
        # The variable contains the number of files 
        # among front-$j-*.txt that has both string AAAAA and BBBBB
        declare count_$ii_$j=$(grep -l AAAAA $(grep -l BBBBB $i/result/list-$NUM/text/front-$j-*.txt) | wc -l)

        # If the variable is empty,then put 0.
        # Some folders does not contain all front-$j=*.txt
        count_$ii_$j=${count_$ii_$j/NULL/0}

        # Print out
        results="$i     $j     $count_${ii}_${j}"
        echo -e "$results" > result.txt
     done
done

此脚本不起作用。我能看到的是

test.sh: line 22: count_$ii_$j=${count_${ii}_${j}/NULL/0}: bad substitution

如果我删除第 22 行并执行,则

grep: 0000/result/list-$NUM/text/front-$j-*.txt: No such file or directory

确实有些文件夹没有所有 $j 索引的 front-$j-*.txt。所以“没有这样的文件或目录”是预期的结果。

但是,我不确定为什么会出现“不良替代”。我怀疑变量名中索引 ii 和 j 的错误转义,因为我使用了 ii 而不是 i 来防止八进制值错误

这也与打印部分有关,我不确定我是否正确打印出目标值(我的意思是,我不确定 $count_${ii}_${j} 是否为正确的在“”内)。

此外,我也怀疑这种方法/策略:在命令替换中使用 $(grep ~~~ | wc -l) 来计算目标文本文件间的出现次数。如果没有找到目标文件,首先使用 if 结构来计算目标文件的出现次数并用 0 替换空变量会更好吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)