bash - 将数字作为命令行参数并打印计数

标签 bash shell

我想将数字作为命令行参数并打印 以 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

尝试山:

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
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]+)/\2\t\t\1/'  #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

关于bash - 将数字作为命令行参数并打印计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71626925/

相关文章:

shell - "Hiding"来自 ltrace 和 strace 的系统调用

linux - Bash/SH,相同的命令不同的输出?

linux - 使用需要输入的命令在脚本内部执行 sudo (bash)

linux - 以自然方式对制表符分隔的文本文件的字母数字和数字列进行排序

mysql - 如何在 ubuntu 中使用脚本添加带有连字符的数据库名称

java - jline 在底部保持提示

linux - Ubuntu shell 脚本将目录的第二个文件保存为变量

node.js - git bash 找不到模块 npm-cli.js

将单词附加到文件名的 bash 脚本

bash - 一个 sourced bash 片段如何有条件地为 sourcing shell 提供一个功能?