为命令的重复结果生成唯一标签

Generate unique tags to repeating results of a command

我有一个脚本 运行 可以生成连续输出,例如:

/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 个部分组成(如上所述的字符串、字符串、整数)。我需要根据每行的第一个字符串为每一行分配一个唯一标识符,创建如下输出:

/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

关于如何实现他的目标有什么建议吗?

纯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的解决方案(感谢!):

#!/bin/bash

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

或者在 Perl 中:

my $i = 1;
my %d;
while (<>) {
  chomp;
  my ($id, @r) = split;
  $id =~ s#^/##;
  unless (exists $d{$id}) {
    $d{$id} = $i++;
  }
  print "/$d{$id} $id @r\n";
}