Search code examples
linuxbashmacosmacos-sierra

Extract part of string in Bash


When I import my GPG keys, I get a response back:

gpg: key LOL12345: public key "John Doe (Developer) <[email protected]>" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)

I would very much like to extract the key's ID LOL12345.

The command I run that returns the output is as follows:

gpg --import "public.key"

Solution

  • Try to use grep:

    yourCommand | grep -Po -m 1 'gpg: key \K\w+'
    

    -P use perl regex style.
    -o print only the matched part.
    -m 1 exit after the first match. This will ensure, that the key is not printed multiple times.
    \K once matched, forget the matched part left of \K.
    \w+ Match as many alphanumeric characters as possible.