Search code examples
regexbashmacosgrepkeychain

Why does grep not extract from security utility's output? Comparable extraction from echo works


In OS X, there is a command-line utility called security which is designed to access the Keychain. It can return the password of an entry in the Keychain, which is what I'm trying to do. When I run security find-internet-password -ga an_entry | grep "password" I get the following output, as expected:

password: "apassword123"

I would like to extract the text between the quotes. grep, specifically pcregrep, should work but doesn't:

echo 'password: "apassword123"' | pcregrep -o '^password:\s"(?!_)\K[^"]+'

Returns:

apassword123

As expected, but:

security find-internet-password -ga anentry | pcregrep -o '^password:\s"(?!_)\K[^"]+'

Returns:

password: "apassword123"

Which is absurd.


Solution

  • Your output actually doesn't get through the grep as it's on stderr. You should be able to do this by redirecting the stderr to stdout like

    security find-internet-password -ga anentry 2>&1 | pcregrep -o '^password:\s"(?!_)\K[^"]+'