来自文件的累计计数值
Cumulative counting values from files
我需要将几个文件中的数字提取到一个累积变量中,并如图所示为每个父目录打印该变量
├───Parent1
│ ├───20210824_2000
│ │ ├───200000_child1
│ │ │ report.md
│ │ │ log.log
│ │ │ file.xml
│ │ │ input.json
│ │ │
│ │ ├───200030_child2
│ │ │
│ │ ├───200034_child3
│ │ │
│ │ ├───200039_child4
│ │ ...
│ ├───20210825_0800
│ │ ├───200000_child1
│ │ │ report.md
│ │ │ log.log
│ │ │ file.xml
│ │ │ input.json
│ │ │
│ │ ├───200030_child2
│ │ │
│ │ ├───200034_child3
│ │ │
│ │ ├───200039_child4
│ │ ...
│ ...
├───Parent2
│ ├───20210824_2000
│ │ ├───200000_child1
│ │ │ report.md
│ │ │ log.log
│ │ │ file.xml
│ │ │ input.json
│ │ │
│ │ ├───200030_child2
│ │ │
│ │ ├───200034_child3
│ │ │
│ │ ├───200039_child4
│ │ ...
│ ├───20210825_0800
│ │ ├───200000_child1
│ │ │ report.md
│ │ │ log.log
│ │ │ file.xml
│ │ │ input.json
│ │ │
│ │ ├───200030_child2
│ │ │
│ │ ├───200034_child3
│ │ │
│ │ ├───200039_child4
│ │ ...
│ ...
...
我似乎无法将 grep 输出提取到数字变量中。子文件夹附有时间戳,所以我排序,因为我只想要最新的文件。
这是我目前的情况:
#!/bin/bash
find . -type d -iname 'parent*' | while read -r dir; do
sum=0;
find "$dir" -maxdepth 1 -type d | sort -r | head -1 |
(
while read -r subdir; do
count="$(find "$subdir" -type f -iname '*report.md' -exec grep -ohP '(?<=\*)\d+(?=\*+ number of things)' {} \+)"
sum=$((sum + count))
done
basename "$dir" "$sum"
)
done
但这似乎并不想将 count
添加到 sum
它只是将 count
打印到每个文件的控制台。
由于每次while创建的子shell有问题,所以变量不是全局的,你可以在“Shell variables set inside while loop not visible outside of it”
中找到有用的信息计数变量也可能有问题,因为查找应该 returns 多行。
试试这个:
#!/bin/bash
find . -type d -iname 'parent*' | while read -r dir; do
sum=0;
while read -r subdir; do
while read report; do
count="$(grep -ohP '(?<=\*)\d+(?=\*+ number of things)' $report)"
sum=$((sum + count))
done < <(find "$subdir" -type f -iname '*report.md')
done < <(find "$dir" -maxdepth 1 -type d | sort -r | head -1)
folder=$(basename $dir)
echo "$folder $sum"
done
注意done < <(
中的空格。
没测试过,不好意思