生成唯一的标签命令的重复结果(Generate unique tags to repeating r

2019-10-22 06:33发布

我有一个脚本运行,其产生连续输出如:

/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个部分(字符串,字符串,如上面INT)。 我需要分配基于每一行的第一个串的唯一标识符的每一行,创建这样的输出:

/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

至于如何他可以实现任何建议?

Answer 1:

纯击溶液:

#!/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


Answer 2:

或在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";
}


文章来源: Generate unique tags to repeating results of a command
标签: bash shell tags