You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Shell/Bash统计域名与关键词映射对的出现频率?

Shell脚本实现域名与关键词映射对的次数统计方案

作为Shell脚本新手完全没思路很正常,我来一步步帮你实现这个需求,保证每一步都讲清楚~

核心思路拆解

  1. 优先匹配长关键词:因为你的关键词里有包含关系(比如Hello World包含Hello),必须先检测长关键词,不然会出现统计错误。
  2. 逐行处理数据:从每一行里提取域名,然后在剩余文本中匹配对应的关键词,找到映射后的hX标识。
  3. 统计组合次数:用一个关联数组记录域名_Key的组合出现次数,最后再格式化输出。

完整实现脚本

#!/bin/bash

# 1. 定义你的关键词映射关联数组
declare -A keywords=( ["Hello World"]="h1" ["Hello"]="h2" ["Hi there"]="h3" )

# 2. 定义统计用的关联数组,用「域名_Key」作为唯一键
declare -A count_map

# 3. 把关键词按长度从长到短排序,确保长关键词优先匹配
sorted_keywords=$(printf "%s\n" "${!keywords[@]}" | awk '{print length, $0}' | sort -nr | cut -d' ' -f2-)

# 4. 逐行读取数据文件(这里假设数据存在data.txt中,可替换成你的数据源)
while read -r domain rest_content; do
    matched_key=""
    # 遍历排序后的关键词,找到第一个匹配的
    for kw in $sorted_keywords; do
        if [[ "$rest_content" == *"$kw"* ]]; then
            matched_key=${keywords[$kw]}
            break  # 找到匹配就停止,避免重复匹配
        fi
    done

    # 如果匹配到关键词,更新统计
    if [[ -n "$matched_key" ]]; then
        combined_key="${domain}_${matched_key}"
        ((count_map[$combined_key]++))
    fi
done < "data.txt"

# 5. 按要求格式输出结果
echo "A Key Count"
for item in "${!count_map[@]}"; do
    # 拆分「域名_Key」为单独的域名和Key
    domain_part=${item%_*}
    key_part=${item#*_}
    echo "$domain_part $key_part ${count_map[$item]}"
done

使用说明

  1. 把你的数据保存成data.txt文件,内容就是你提供的那几行:
    abc.com Hello World Ann
    abc.com Hi there friend
    def.com Hello Sam
    def.com Hello Dan
    abc.com Hello World Mary
    
  2. 把上面的脚本保存为count_stat.sh,然后给脚本加执行权限:
    chmod +x count_stat.sh
    
  3. 运行脚本就能得到你想要的结果:
    ./count_stat.sh
    

关键细节解释

  • 关键词排序:用awk获取关键词长度,sort -nr倒序排序,确保长关键词先被检测,避免Hello World被错误识别为Hello。
  • 关联数组统计:用域名_Key作为键,能保证每个组合唯一,比如abc.com_h1就是一个独立的统计项。
  • 逐行读取:read -r domain rest_content会自动把每行第一个字段作为域名,剩下的所有内容作为待匹配文本,完美适配你的数据格式。

内容的提问来源于stack exchange,提问作者user2340345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:38:31