首页 > 解决方案 > 在文件夹的文件中查找随机生成的数字的总和

问题描述

我有一个大学的任务是创建 5 个文件夹,每个文件夹里面有 10 个文件,然后在所有文件中随机生成 10 个数字,最后计算每个文件夹中文件中数字的总和,并将它们输出到一个单独的文件中。我们只学习了基础知识,我很难理解下一步该做什么。我已经设法在里面创建了带有随机数字的文件夹和文件,但我不知道如何遍历每个文件夹并对每个文件中的数字求和。有人可以帮我吗?

#!/bin/bash
mkdir Katalogas1
mkdir Katalogas2
mkdir Katalogas3
mkdir Katalogas4
mkdir Katalogas5
for x in {1..10}
for x in {1..10}
do 
touch "$x.txt"
shuf -i1-1000 -n 1 >Katalogas1/$x.txt
done
paste 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 10.txt >bendras1.txt
cat bendras1.txt | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,($1+$2+$3+$4+$5+$6+$7+$8+$9+$10)}' >katalogas1.txt
cd ..
cd Katalogas2
for x in {1..10}
do 
touch "$x.txt"
shuf -i1-1000 -n 1 >Katalogas2/$x.txt
done
paste 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 10.txt >bendras2.txt
cat bendras2.txt | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,($1+$2+$3+$4+$5+$6+$7+$8+$9+$10)}' >katalogas2.txt
cd ..
cd Katalogas3
for x in {1..10}
do 
touch "$x.txt"
shuf -i1-1000 -n 1 >Katalogas3/$x.txt
done
paste 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 10.txt >bendras3.txt
cat bendras3.txt | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,($1+$2+$3+$4+$5+$6+$7+$8+$9+$10)}' >katalogas3.txt
cd ..
cd Katalogas4
for x in {1..10}
do 
touch "$x.txt"
shuf -i1-1000 -n 1 >Katalogas4/$x.txt
done
paste 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 10.txt >bendras4.txt
cat bendras4.txt | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,($1+$2+$3+$4+$5+$6+$7+$8+$9+$10)}' >katalogas4.txt
cd ..
cd Katalogas5
for x in {1..10}
do 
touch "$x.txt"
shuf -i1-1000 -n 1 >Katalogas5/$x.txt
done
paste 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 10.txt >bendras5.txt
cat bendras5.txt | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,($1+$2+$3+$4+$5+$6+$7+$8+$9+$10)}' >katalogas5.txt

标签: bash

解决方案


我告诉过你使用函数

#!/bin/bash

k=("Katalogas1" "Katalogas2" "Katalogas3" "Katalogas4" "Katalogas5")

# one function to make the folders

mfiles()  {
 cd $1
 for x in {1..10}
  do
  touch "$x.txt"
  shuf -i1-1000 -n 1 > $x.txt
 done
 cd ..
}

# one function to go the same way and count the beans 
# and write it to a file in your folders

summ() {
 cd $1
 touch "sum.txt"
 for x in {1..10}
  do
  ((sum += `cat $x.txt`))
 done
 echo "$sum" > "sum.txt"
 cd ..
}

# finally this is your main program

for i in "${k[@]}"; do
    mkdir "$i"
    mfiles "$i"
    summ "$i"
done

推荐阅读