1

I have some hundreds of .doc and .rtf files, which lost their original names after recovery from a damaged hard disk. Basically they look like this:

f132765720.rtf
f136246056.rtf
f146124320.doc
f147595288.docx
f131673632.rtf

I can read the files without any problem. How can I recreate meaningful filenames from files' content in Linux?

Sample file: https://dl.dropboxusercontent.com/u/41225253/example.rtf

0

2 Answers 2

3

The script below will find all .docx and .rtf files in the current directory and rename them to first_few_words.rtf or docx. First you need to install catdoc. On Debian and its derivatives you can do that with

sudo apt-get install catdoc 

Oddly enough, catdoc gives me a segfault when I try it on a docx I have, so use docx2txt for the doc files instead:

sudo apt-get install docx2txt

Once you have catdoc and docx installed, cd to the directory that contains your files and run this:

for file in *rtf; do 
  name=$(catdoc "$file" | grep . | head -1 | sed 's/ /_/g') &&
  mv "$file" "$name".rtf;
done
for file in *docx; do 
  name=$(docx2txt < "$file" | grep . | head -1 | sed 's/ /_/g') &&
  mv "$file" "$name".docx;
done

CAUTION: This will delete the original files, make sure you make a back up first, just in case.

EXPLANATION: both utilities convert docx or rtf to text, I then select the first non empty line of that text, convert spaces to underscores (it will make your life easier in the long run) and rename the files accordingly.

1

To the answer provided by @terdon I'd like to add that I found that if I prefix every file name with a creation date, it would be a big help.

For .docx files date can be found this way:

unzip -p example.docx | grep dcterms:created |
    grep -o [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] | head -1

For .doc files:

antiword -x db example.doc | grep date | grep -o '[0-9-]*'

For .rtf files:

grep -o '\\creatim\\yr[0-9]*\\mo[0-9]*\\dy[0-9]*' example.rtf |
    grep -o [0-9]* | tr "\n" -

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .