Peter Kapteyn
Peter Kapteyn

Reputation: 405

How to grab commit from grep output

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?

Upvotes: 2

Views: 125

Answers (3)

dan
dan

Reputation: 5251

For the commits printed (ten in this case), print the hash of the oldest commit matching pattern:

git log --oneline -n 10 |
awk '$0 ~ /pattern/ {hash = $1} END {print hash}'

Same, but for the Nth newest:

git log --oneline -n 10 |
awk '$0 ~ /pattern/ && ++c==N {print $1}'

(use 1 for newest, or 2 for second newest, etc, N must be <= 10 in this example)

Print hash of Nth newest commit (no pattern):

git log --oneline -n N |
awk 'END {print $1}'

Or

git log --oneline |
awk 'NR==N {print $1}'

Remember that git log has the options --since, --after, --until, and --before, which take a date as input.

Upvotes: 1

Peter Kapteyn
Peter Kapteyn

Reputation: 405

My friend just showed me this:

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

But I'm interested to see if anyone has any different solutions.

Upvotes: 2

anubhava
anubhava

Reputation: 786289

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.

Upvotes: 2

Related Questions