Generate unique tags to repeating results of a com

2019-08-09 02:19发布

问题:

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

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?

回答1:

A pure Bash solution:

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

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


回答2:

Or in 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";
}


标签: bash shell tags