Skip to content
Advertisement

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) <john@doe.com>" 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"

Advertisement

Answer

Try to use grep:

yourCommand | grep -Po -m 1 'gpg: key Kw+'

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement