George George - 18 days ago 5
Git Question

Using Git to Figure out How Long a Line of Text Has Been In a File

Suppose we have a

file1.txt
in a git repository. Suppose this file has a line of text:
an old line of text
.

Is there a way to figure out, through git (or some other Unix utility?) how many days this line of text has been in this file?

Answer

You can use

datefrom=$(git log --pretty=format:'%cd' --date=format:'%Y-%m-%d' -S 'line to find' -- file1.txt)

That will result in date of commit that introduced that string.

  • log searches commit history
  • -S option finds first introduction of a string
  • --pretty=format:'%ad' prints committer date
  • --date=format obviously formats the date

Now from this: http://unix.stackexchange.com/questions/215934/whats-a-smart-way-to-count-the-number-of-days-since-x you get:

echo $(( (`date +%s` - `date +%s -d $(datefrom)`) / 86400 ))

which results in number of days from introducing commit.

Ofcourse you can put everything in one command and make an alias, or you can create git-command-name script and put it into user/bin folder and git will recognize it as git command that you can invoke with

git command-name 'line to find'