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?
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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.