How to extract the commit ID alone from the full commit message in shell script

I tried fetching only the commit ID from the commit message in the shell script, I need only "d1099308a1af0f91e93bf22cf6e9b5d294cf121d"

commit_message = "commit d1099308a1af0f91e93bf22cf6e9b5d294cf121d Author: Martin Date: Wed Apr 17 16:05:35 2019"

I tried using the following sed command, but it is not working commit_ID=$( sed -e 's/commit .(*) Author/' $commit_message )

Upvotes: 1

Views: 899

Answers (3)

nbari
nbari

Reputation: 27005

Give a try to:

egrep -o "[a-f0-9]{40}" log.txt

This will return only the git commit ID SHA-1 hashes (40 digits long).

Upvotes: 0

UtLox
UtLox

Reputation: 4164

You mean something like that?

sed 's/^commit \([^ ]*\).*/\1/' <<< $commit_message

output

d1099308a1af0f91e93bf22cf6e9b5d294cf121d

Upvotes: 1

virolino
virolino

Reputation: 2227

If you do not have other ID's, this regex will work:

[0-9a-fA-F]{20,}

If there are other ID's, then adding a look behind will help filtering:

(?<="commit\s)[0-9a-fA-F]{20,}

However, the "s" command of sed does not fetch, it "substitutes". For fetching, you may want to use "grep" or others.

Upvotes: 1

Related Questions