我是 bash 脚本的新手,所以有些语法可能不是最佳的。如果你看到一个,请指出它们。
我在按顺序命名的目录中有文件。
示例:prob01_01 prob01_03 prob01_07 prob02_01 prob02_03 ....
我试图让脚本遍历当前目录并计算每个问题有多少个扩展名。然后打印预扩展名然后计数
上面的示例输出是:
概率01 3
概率 2
这是我的代码:
#!/bin/bash
temp=$(mktemp)
element=''
count=0
for i in *
do
current=${i%_*}
if [[ $current == $element ]]
then
let "count+=1"
else
echo $element $count >> temp
element=$current
count=1
fi
done
echo 'heres the temp:'
cat temp
rm 'temp'
问题:
当前输出:
概率 1 3
期望的输出:
概率 1 3
概率 2
没有附加最后一个计数,因为它后面没有看到不同的元素
我对可能解决方案的猜测:
最后一个追加是否发生在 for 循环的末尾?
最佳答案
你的代码有两个问题。
第一个问题没有回答你的问题。您创建一个临时文件,文件名存储在 $temp
中。您应该使用那个文件,而不是具有固定名称 temp
的文件。
问题是您只在看到新问题/文件名时才写入结果。最后一个不会打印。
仅修复这些问题将导致
results() {
if (( count == 0 )); then
return
fi
echo $element $count >> "${temp}"
}
temp=$(mktemp)
element=''
count=0
for i in prob*
do
current=${i%_*}
if [[ $current == $element ]]
then
let "count+=1" # Better is using ((count++))
else
results
element=$current
count=1
fi
done
results
echo 'heres the temp:'
cat "${temp}"
rm "${temp}"
你可以不用脚本
ls prob* | cut -d"_" -f1 | sort | uniq -c
当您希望按给定的方式显示输出时,您还需要一个步骤。
ls prob* | cut -d"_" -f1 | sort | uniq -c | awk '{print $2 " " $1}'
关于linux - bash 计算顺序文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53129475/