in reply to Re^2: Extracting password from array
in thread Extracting password from array

I'd like to see this shell solution

Replies are listed 'Best First'.
Re^4: Extracting password from array
by Anonymous Monk on Mar 26, 2010 at 18:45 UTC

    Untested

    egrep "^$1:[^:]*:$2:" | cut -d':' -f2
      You hadn't specified the arguments were regex patterns, not text.
      perl -le'while(<STDIN>) { print $1 if /^$ARGV[0]:([^:]*):$ARGV[1]:/ }'
      If they are actually text, then you can easily solve that for the Perl version.
      perl -le'while(<STDIN>) { print $1 if /^\Q$ARGV[0]\E:([^:]*):\Q$ARGV[1 +]\E:/ }'

      Using split is bit longer, but more readable.

      I forgot to include the file name, but I think you get the idea.
Re^4: Extracting password from array
by robotball (Initiate) on Mar 29, 2010 at 19:02 UTC
    Shell solution would be PASSWD=`cat password_file | grep $database | grep $user | cut -d: -f2`

      And you're complaining about the code I gave? I can't wait for the day you create a user name, password, database name or server name that's a subset of a user name, password, database name or server name (which doesn't seem unlikely).

      The direct equivalent of:

      database=... user=... PASSWD=`cat password_file | grep $database | grep $user | cut -d: -f2`
      is
      my $database = '...'; my $user = '...'; my $PASSWD = ''; open(my $fh, '<', 'password_file') or die("open: $!\n"); while (<$fh>) { chomp; $PASSWD = (split /:/)[2] if /$database/ && /$user/; }

      Not bad. Replacing 4 entire programs with 5 statements. (Although cat is totally useless in your code.)

      If you want an equivalent drop-in replacement, you can use

      PASSWD=`perl -e"chomp; print((split /:/)[2]) if /$database/ && /$user/ +" < password_file`

      If you want a better drop-in replacement, you can use

      PASSWD=`perl -F: -lane'print $F[1] if $F[2] eq $ARGV[0] && $F[0] eq $A +RGV[1]' $database $user < password_file`