It happens, you accidentally delete a file and you need it back. Maybe you don’t do backups (shame on you). Maybe your most current backup isn’t good enough. Whatever the reason many people, myself included, have accidentally removed something that they need back. Here is a quick trick that might save you.
grep -a -B 25 -A 100 'some string in the file' /dev/sda1 > results.txt
“-a” – treat the drive (binary) as text
“-B 25 -A 100″ – print 25 lines before a match and 100 lines after
The search string must be something you know was in the file you removed that is likely to be unique.
It’s probably a good idea to write the output on a different partition than the one you are searching. You can also substitute something like “-C 100″ for the -B/-A switches. The -C switch is short hand for the arguement number of lines both before and after the match.
via Atomic Spin
If you work at all in Solaris (and maybe just older versions I don’t know) you will eventually find out that the version of “grep” shipped with the OS is missing the “-r” option for doing recursive greps. Over the years I have found myself becoming a huge fan of this ability and I am always amazed to find there are versions that don’t include it. Today I set out to come up with a way to emulate the behavior.
I came up with two solutions. First we have:
find . |xargs grep PATTERN
While this seemed to work fine at first I noticed that it had issues with file that contained spaces. It would treat each “word” of a file name with spaces as a separate filename and I would get errors from grep about not being able to find the file. If you know that you don’t have any filenames with spaces though the above should work just fine.
As I played around further I managed to come up with the following second iteration:
find . -exec grep PATTERN {} /dev/null \;
This one worked just as well as the first one but had the added advantage of treating file names with spaces in the correctly. I don’t claim to be a find master. Unfortunately I can’t tell you why the “/dev/null” is required except that I can tell you without it you will get the lines in files matching the pattern returned but not the filename the line is contained in.
I found an article over at Linux Journal that lead with the sentence:
When grep and sed aren’t enough, gawk may provide the extra horsepower that you need.
I would have to argue against that. Nothing personal against gawk, awk itself, or any of it’s variants. I personally love awk. Though I would rewrite their first sentence a bit.
When grep and sed aren’t enough, you obviously don’t know enough grep and sed.
At any rate he does provide some gawk examples that aren’t totally worthless but certainly don’t require it over grep and/or sed. I am guessing that there will be some decent examples either way in the comments section as well.