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

Thanks. I guess I was trying to do to many tricks thinking this could be a one-liner like if you were to use shell.

Replies are listed 'Best First'.
Re^3: Extracting password from array
by ikegami (Patriarch) on Mar 26, 2010 at 17:50 UTC
    I'd like to see this shell solution

      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.
      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`