题解 | #netstat练习3-输出每个IP的连接数#

netstat练习3-输出每个IP的连接数

http://www.nowcoder.com/practice/f601fc4f35b5453ba661531051b6ce69

#! /usr/bin/env bash

########################################################
#
#
########################################################
function solution_1() {
    grep tcp nowcoder.txt | awk -F":" '{print $2}' | awk '{print $2}' | sort | uniq -c | awk '{print $2,$1}' | sort -nr -k2
}

########################################################
#
#
########################################################
function solution_2() {
    awk '{
        if($1 == "tcp") {
            split($5, arr, ":");
            a[arr[1]]++;
        }
    } END {
        for(k in a) {
           print k,a[k]
       }
    }' nowcoder.txt | sort -nrk2
}

########################################################
#
#
########################################################
function solution_3() {
    local condition_index=${1}
    local target_index=${2}
    declare -A map
    local array=""
    local old_ifs=${IFS}
    while read line; do
        array=(${line})
        if [[ ${array[${condition_index}]} = "tcp" ]]; then
            IFS=":"
            array=(${array[${target_index}]})
            IFS="${old_ifs}"
            (( map["${array[0]}"]++ ))
        fi
    done < nowcoder.txt

    local tmp=(${map[@]})
    local size=${#tmp[@]}
    local int=0
    for (( i = 0; i < ${size}; i++ )); do
        for (( j = $i + 1; j < ${size}; j++ )); do
            [[ ${tmp[$i]} -ge ${tmp[$j]} ]] && continue
            int=${tmp[$i]}
            tmp[i]=${tmp[$j]}
            tmp[$j]=$int
        done
    done

    for (( i = 0; i < size; i++ )); do
        for va in ${!map[*]}; do
            [[ ${tmp[$i]} = ${map[$va]} ]] && printf "$va ${map[$va]}\n"
        done
    done
}

#solution_1
solution_2
# 有相同数量的结果,因此遍历输出是不正确的,有重复
#solution_3 0 4
全部评论

相关推荐

05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
07-03 16:02
门头沟学院 Java
今天面试,非常紧张,面试官问我springboot有哪些核心模块都答不上来了,真的对自己无语了!
程序员小白条:28届我勒个去,很多人面试都没机会
查看1道真题和解析
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务