Linux: recover deleted text files using grep

Recently i did a mistake, i accidentally deleted a script on my file system that had tool about a week to complete it, i started exploring…

Linux: recover deleted text files using grep
Photo by Sam Pak on Unsplash

Recently i did a mistake, i accidentally deleted a script on my file system that had tool about a week to complete it, i started exploring ways to recover the file but none worked for me except one! “grep” now you will wonder how grep can recover files! well it cannot! let me explain: “when you delete a file using a command such as rm the actual data do not get deleted immediately unless other data is written to the same disk place as the deleted file”. Now here comes grep, in Linux everything can be treated as file even the disk partitions, this means that we can grep the partitions and search for ASCII data (clear text files).

In my case the deleted file was a python script which the first line was#!/usr/bin/env python

And the length of file was about 300 lines.

The partition that i deleted the file as /dev/sdc , then i tried the following$ sudo grep --binary-files=text -A 300 '/usr/bin/env python3' /dev/sdc | tee recover_data

  • sudo grep : run grep as root
  • binary-files=text :
  • -A 300 : print the next 300 lines after the match
  • /usr/bin/env python3 : what to match
  • /dev/sdc : my partition
  • tee recover_data : print to screen but also write the matches in recover_data

When the script completed it created a huge file with ASCII and non ASCII characters, since i was looking a script there is no meaning to keep non-ASCII characters, i cleared out non-ASCII with the strings command$ cat recover_data | strings > clear_data.txt

clear_data.txt contained my script but also many other scripts that contain the same line that i was trying to match, this makes the things a bit difficult but way easier than re-writing the script!

I hope you found this article useful is i did :)

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…