kayaker243
kayaker243

Reputation: 2638

Stage only those files containing a specific change in Git

I want to upgrade to a newer version of a CMS whose development is tracked in Git. Since the CMS update is in the new year, every file gets the copyright date bumped from 2011 to 2012.

I could visually inspect and stage each file that just gets the copyright bump using git gui. However, it seems like I should be able to tell git to stage only those files whose only change is:

- * @copyright  Copyright (c) 2008 - 2011, EllisLab, Inc.
+ * @copyright  Copyright (c) 2008 - 2012, EllisLab, Inc.

There are a few thousand files that changed, but the vast majority of these received no other change than this specific line. I want to stage and commit this simple copyright date bump, then take a closer look at those files receiving more substantive changes.

This purpose could be accomplished by two possible means:

  1. Stage and commmit only those files that just contain this change.
  2. Stage and commit just this change from all files.

Is either possible? Thanks in advance!

Upvotes: 4

Views: 456

Answers (3)

hmottestad
hmottestad

Reputation: 21

For mac users the following works:

git add `git diff -G 'YOUR_REGEX_GOES_HERE' --name-only` 

Upvotes: 0

Franklin P Strube
Franklin P Strube

Reputation: 2215

I recently had to do the exact thing for a Magento upgrade. 90% of the changes were just updated copyright lines. So I figured out the following "one-liner".

git diff -G '@copyright.*[Cc]opyright' --name-only | xargs -I {} sh -c 'FILE={} ; [ $(git diff -U0 -- $FILE | wc -l | tr -d " " | cut -f1-) -eq 7 ] && git add $FILE'

If you want to be safe and verify things first, change the last part to 'echo git add $FILE', so that it only prints out the command.

Upvotes: 4

Luke H
Luke H

Reputation: 3163

I'm afraid I've answered in reverse order, but...

2 Stage only those lines:

 git add --patch

It's a fairly manual method, though, so maybe this saves some time, allowing you to only review those with relevant change,

for i in $(gd -SYOURCHANGESTRING | sed -rn 's/^diff --git a\/(\S+).*$/\1/p'); do git add --patch "$i"; done

1 Stage ALL those files with changed string.

Something like this:

git diff -SYOURCHANGESTRING | sed -rn 's/^diff --git a\/(\S+).*$/\1/p' | xargs -n1 git add

Upvotes: 1

Related Questions