Find the answer to your Linux question:
Results 1 to 3 of 3
Trying to bash script the following with no luck at all. Please help. THANKS! Convert a file that has random usernames with a varing number of multiple random IP's on ...
  1. #1
    Just Joined!
    Join Date
    May 2011
    Posts
    2

    Bash Loop Script to join lines while a field is unchanged

    Trying to bash script the following with no luck at all. Please help. THANKS!

    Convert a file that has random usernames with a varing number of multiple random IP's on multiple lines to one line per username with all of the IP's on the same line:

    Ex:
    Convert this:

    usernameA,10.19.43.67
    usernameA,172.19.240.5
    usernameA,192.168.4.3
    usernameB,10.23.14.8
    usernameB,172.22.22.14

    To this:

    usernameA,10.19.43.67,172.19.240.5,192.168.4.3
    usernameB,10.23.14.8,172.22.22.14

  2. #2
    Just Joined!
    Join Date
    May 2011
    Posts
    2

    Well I guess I'll post the fix myself then

    awk '
    BEGIN {
    RS = "[\t\n\v\f\r ]*[\n\r][\t\n\v\f\r ]*"
    FS = ",[\t\v\f ]*"
    users = 0
    }

    (NF > 1) {
    if (!($1 in list)) {
    user[++users] = $1
    list[$1] = ","
    }
    for (i = 2; i <= NF; i++)
    if (length($i) > 0)
    if (!index(list[$1], "," $i ","))
    list[$1] = list[$1] $i ","
    }

    END {
    for (u = 1; u <= users; u++) {
    thisuser = user[u]
    thislist = list[thisuser]
    sub(/^,+/, "", thislist)
    sub(/,+$/, "", thislist)
    printf("%s:%s\n", thisuser, thislist)
    }
    }' filename

  3. #3
    Just Joined!
    Join Date
    May 2011
    Posts
    44
    Here's my crack at it in Perl...
    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my %users;
    open my $FHIN, '<', $ARGV[0];
    foreach (<$FHIN>){
      my ($user, $ip) = split/,/;
      $users{$user} .= ",$ip";
    }
    
    print "$_$users{$_} \n" foreach keys %users;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...