How to recover a file overwritten with another in Linux?

Solution 1:

Some people suggest

su
umount /home
grep -a -A800 -B800 'target' /dev/sda2 | strings > recovered_file

These lines assume that your file was in the /home filesystem, /home was mounted on the partition /dev/sda2, and 'target' is a key phrase that is likely to be unique to the overwritten file. The option -a handles all binary files as text documents, the options -A800 and -B800 show 800 lines after and before a match with 'target'.
The command strings extracts text files for the stream of tokens coming out of grep. If you are on a live USB, this command may not be available but you should be able to install it nonetheless from the repository.

recovered_file is likely to be large but has a chance of containing text from the overwritten file. If the overwritten file was not primarily text, this approach is not useful.

It is important to take measures to prevent the operating system making further writes to the filesystem that contains your file. A good way is to boot from a live CD/USB. If you can unmount the filesystem or remount it read-only, that is also good.


You may find it interesting to read http://carlo17.home.xs4all.nl/howto/undelete_ext3.html - though that applies more to deleted files than to overwritten ones. However if you previously edited your overwritten file, it is likeley that the editor left several deleted copies on disk as a natural part of the editing process.

Solution 2:

Stop using/dismount the corresponding partition asap.

Consider this thread where extundelete is mentioned. Also, there exist photorec, foremost, and scalpel which are very powerful file carvers that may help recovering your file (e.g. by finding older versions or backups of your file that have not been overwritten yet).

All of these tools are available in your Ubuntu apt repositories (photorec comes with the testdisk package).

Remember to save the recovery results on another partition than the one where you recover your data from.

However, if your file has indeed been overwritten (i.e. the same area of the hard disk where the old file was stored has been used to store the new file) then there is no possibility to recover the file (Note: This is only valid for hard disks - ssds store (and "overwrite") files in another way). If you are lucky then you may only be able to recover parts of the file that were not overwritten, e.g. if the new file was smaller than the old one.