数字作为命令行参数并打印计数
numbers as command-line arguments and prints the count
我想将数字作为命令行参数并打印数量
以 0、1、2 等结尾的数字,最多 5 个。
示例:
bash test.sh 12 14 12 15 14
预期输出:
Digit_ends_with count
0 0
1 0
2 2
3 0
4 2
5 1
Mt 尝试:
read -a integers for i in ${integers[@]} do if [[ grep -o '[0-9]' $i ]] count=$(grep -c $i) if [ "$count" -ge "0" ] then
echo "Digit_ends_with" $i echo -e "Count ""$count" fi fi done
但这不起作用。我怎样才能达到这个要求?
请您尝试以下操作:
#!/bin/bash
for i in "$@"; do # loop over arguments
(( count[i % 10]++ )) # index with the modulo 10
done
printf "%s %s\n" "Digit_ends_with" "count" # header line
for (( i = 0; i < 6; i++ )); do # loop between 0 and 5
printf "%d\t\t%d\n" "$i" "${count[$i]}" # print the counts
done
./test.sh 12 14 12 15 14
的结果:
Digit_ends_with count
0 0
1 0
2 2
3 0
4 2
5 1
#!/bin/bash
echo "Digit_ends_with count" #print table header
for argument in "$@" #loop over all given arguments
do
current=$(echo "$argument" | tail -c 2 ) #get last digit
if (( "$current" <= 5 )) #check if lower than 6
then
echo "$current" #echo if true
fi
done | sort | uniq -c | sed -E 's/\s+//' | sed -E 's/([0-9]+).?([0-9]+)/\t\t/' #sort, count, remove leading spaces and switch the fields
示例:
╰─$ ./test.sh 188 182 182 12 13 14 18 15 16 17 18 19 10 0 0 0 0 0 0 0 0 0 0
Digit_ends_with count
0 11
2 3
3 1
4 1
5 1
我想将数字作为命令行参数并打印数量 以 0、1、2 等结尾的数字,最多 5 个。
示例:
bash test.sh 12 14 12 15 14
预期输出:
Digit_ends_with count
0 0
1 0
2 2
3 0
4 2
5 1
Mt 尝试:
read -a integers for i in ${integers[@]} do if [[ grep -o '[0-9]' $i ]] count=$(grep -c $i) if [ "$count" -ge "0" ] then
echo "Digit_ends_with" $i echo -e "Count ""$count" fi fi done
但这不起作用。我怎样才能达到这个要求?
请您尝试以下操作:
#!/bin/bash
for i in "$@"; do # loop over arguments
(( count[i % 10]++ )) # index with the modulo 10
done
printf "%s %s\n" "Digit_ends_with" "count" # header line
for (( i = 0; i < 6; i++ )); do # loop between 0 and 5
printf "%d\t\t%d\n" "$i" "${count[$i]}" # print the counts
done
./test.sh 12 14 12 15 14
的结果:
Digit_ends_with count
0 0
1 0
2 2
3 0
4 2
5 1
#!/bin/bash
echo "Digit_ends_with count" #print table header
for argument in "$@" #loop over all given arguments
do
current=$(echo "$argument" | tail -c 2 ) #get last digit
if (( "$current" <= 5 )) #check if lower than 6
then
echo "$current" #echo if true
fi
done | sort | uniq -c | sed -E 's/\s+//' | sed -E 's/([0-9]+).?([0-9]+)/\t\t/' #sort, count, remove leading spaces and switch the fields
示例:
╰─$ ./test.sh 188 182 182 12 13 14 18 15 16 17 18 19 10 0 0 0 0 0 0 0 0 0 0
Digit_ends_with count
0 11
2 3
3 1
4 1
5 1