Tuesday, January 4, 2022

[SOLVED] How to grab commit from grep output

Issue

Say I call the following command in a git repo:

git log --oneline -n 10 | grep pattern

and it gives me the following output:

c95383f asdfasdf pattern
3e34762 asdfasdfsd pattern

How can I grab just the commit hash from the second line so that I can pipe it into another command?


Solution

You can consider awk for this:

git log --oneline -n 10 | awk '/pattern/ {print $1}'

Where /pattern/ matches pattern in a line while {print $1} prints first field from a matching line.



Answered By - anubhava