Add a JIRA ticket to a batch of old commits

Many software companies use the convention of adding JIRA ticket numbers to all commits.

Adding a JIRA number to new commits is easy with this guide:

The problem

What if you have MANY old commits that are missing JIRA numbers?

The solution

We can do this using git filter branch and sed. Steps below:

  1. Find the oldest commit hash on your branch, for example aabb11
  2. Get a JIRA ticket number that you want to add to commits that don’t already have one. For example, JIRA-1234
  3. On feature branch, run the command below. Replace `JIRA-1234` with your own JIRA ticket placeholder, and `aabb11` with the oldest commit you want to fix

The code

git filter-branch -f --msg-filter "sed -E '/^[0-9A-Z]+-[0-9]+/! s/^/JIRA-1234 /'" aabb11..HEAD


  • git filter-branch will loop over a range of commits
  • We pass it the oldest (aabb11) and the latest (HEAD)
  • For each commit message, it executes a command line string we pass
  • Our command uses sed to edit the commit message
  • Sed takes a regex that checks for JIRA numbers. The regex is /^[0–9A-Z]+-[0–9]+/
  • We look for matches NOT containing JIRA numbers using the ! character
  • Then we call sed where the first section ^ is the start of the commit message
  • And the value to add is JIRA-1234
  • So all togher, our final result is adding the JIRA ticket to the start of the commit message!