Daniel Kobe
Daniel Kobe

Reputation: 9825

Find the first occurrence of matching regex after the first occurrence of another regex has been found

My file looks like this

#Default GitHub
Host github.com
  #Username username2
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_username2

Host github-username1
  #Username username1
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_username1

I'd like to find the first username after github.com so it would return in this case, username2.

Upvotes: 0

Views: 566

Answers (2)

Ed Morton
Ed Morton

Reputation: 203209

awk 'f&&/Username/{print $2; exit} /github\.com/{f=1}' file

Upvotes: 0

James Brown
James Brown

Reputation: 37394

To grab first Username after Host github.com:

$ awk '/Host github.com/ {f=1; next} f==1&& /Username/ {f=0; print $2}' file
username2

Upvotes: 1

Related Questions