生成唯一的标签以重复执行命令的结果 [英] Generate unique tags to repeating results of a command

查看:46
本文介绍了生成唯一的标签以重复执行命令的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个脚本,该脚本会生成连续的输出,例如:

I have a script running which generates continuous output such as:

/AtherosC_92:f1:a7  BTHub4-NJ8S -82
/AtherosC_92:f1:a7  BTHub4-NJ8S -81
/95:8c:ed:6d:65:f5  Home245 -84
/AtherosC_92:f1:a7  BTHub4-NJ8S -78
/3d:cc:54:d1:4f:f6  BTWifi2 -82
/Apple_e5:e8:2d SKYBD80F    -71
/Apple_e5:e8:2d SKYBD80F    -71
/Apple_e5:e8:2d SKYBD80F    -72

每行包括3个部分(如上所述,字符串,字符串,整数).我需要根据每行的第一个字符串为每行分配一个唯一的标识符,并创建如下输出:

Each line is comprised of 3 sections (string, string, int as above). I need to assign each line a unique identifier based on the first string of each line, creating an output like this:

/1 AtherosC_92:f1:a7    BTHub4-NJ8S -82
/1 AtherosC_92:f1:a7    BTHub4-NJ8S -81
/2 95:8c:ed:6d:65:f5    Home245 -84
/1 AtherosC_92:f1:a7    BTHub4-NJ8S -78
/3 3d:cc:54:d1:4f:f6    BTWifi2 -82
/4 Apple_e5:e8:2d   SKYBD80F    -71
/4 Apple_e5:e8:2d   SKYBD80F    -71
/4 Apple_e5:e8:2d   SKYBD80F    -72

关于如何实现他的任何建议?

Any suggestions as to how his could be achieved?

推荐答案

纯Bash解决方案:

#!/bin/bash

declare -A seen
tag=0
while read; do
    read -r first _ <<< "$REPLY"
    [[ $first ]] || continue
    if [[ -z ${seen["$first"]} ]]; then
        seen["$first"]=$((++tag))
    fi
    printf '\\%d %s\n' "${seen["$first"]}" "$REPLY"
done


以下内容基于@rici的解决方案(谢谢!):


The following is based on @rici's solution (thanks!):

#!/bin/bash

declare -A seen=()
while read && read -r first _ <<< "$REPLY" ; do
    [[ $first ]] && printf '\\%d %s\n' "${seen["$first"]=$((${#seen[@]}+1))}" "$REPLY"
done

这篇关于生成唯一的标签以重复执行命令的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆