Search code examples
gitgit-gui

How can I stage individual lines from a deleted file in Git?


I have deleted a file from my working tree by splitting it's content up and moving it into seperate files. I've done all this work at once and now I want to commit the changes as individual commits, with each commit moving one section of the big file into a new smaller file.

I.e. I have:

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        deleted:    big.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        small-1.txt
        small-2.txt
        small-3.txt
        small-4.txt

no changes added to commit (use "git add" and/or "git commit -a")

Normally when staging my changes I'd just select the hunks or lines that are relevant for that commit (using git gui, say, or git add -p). But with a deleted file when I try and do this my request is ignored – it's either the whole file or nothing.

I know that I can use git add -N on an untracked file to specify that it will be added, and then select individual lines from that file to add in its first commit. But running git add -N on a deleted file doesn't have the same effect.

So: is there a way I can stage individual lines from a deleted file, and spread that deletion over multiple commits? This is without having to go back, resurrect the file and make the deletions one-by-one, which is of course the brute-force option.


Solution

  • Git does not have this built in, but you can achieve it trivially: just write an empty file into your work-tree.

    cp /dev/null big.txt
    

    or:

    : > big.txt
    

    for instance in a typical Unix/Linux shell. You now have an empty file—zero bytes long—as your big.txt, and you can run git add -p as usual.

    (This doesn't save a lot of effort since git add -p treats the entire deletion as one big hunk, but it might be what you wanted.)