我使用一个名为photorec的软件从损坏的硬盘中恢复了一些Word文档。问题是文件的名称无法恢复;它们都是由一系列数字重命名的。有超过2000个文件要排序,我想知道我是否可以使用一些自动化过程重命名它们。
是否有一个脚本可以用来查找文档中的前10个字母并用它重命名?它必须能够处理具有相同前10个字母的多个文档,因此不能写入具有相同名称的文档。此外,它必须避免使用非法字符(例如'?','*','/'等)重命名文档。
我只有一点Python,C的经验,甚至更少有Linux中的bash编程经验,所以如果我不知道我在做什么,如果我必须写一个新的脚本,那么请耐心等待。
VBScript怎么样?这是一个草图:
FolderName =“C:\ Docs \”
Set fs = CreateObject("Scripting.FileSystemObject")
Set fldr = fs.GetFolder(Foldername)
Set ws = CreateObject("Word.Application")
For Each f In fldr.Files
If Left(f.name,2)<>"~$" Then
If InStr(f.Type, "Microsoft Word") Then
MsgBox f.Name
Set doc = ws.Documents.Open(Foldername & f.Name)
s = vbNullString
i = 1
Do While Trim(s) = vbNullString And i <= doc.Paragraphs.Count
s = doc.Paragraphs(i)
s = CleanString(Left(s, 10))
i = i + 1
Loop
doc.Close False
If s = "" Then s = "NoParas"
s1 = s
i = 1
Do While fs.FileExists(s1)
s1 = s & i
i = i + 1
Loop
MsgBox "Name " & Foldername & f.Name & " As " & Foldername & s1 _
& Right(f.Name, InStrRev(f.Name, "."))
'' This uses copy, because it seems safer
f.Copy Foldername & s1 & Right(f.Name, InStrRev(f.Name, ".")), False
'' MoveFile will copy the file:
'' fs.MoveFile Foldername & f.Name, Foldername & s1 _
'' & Right(f.Name, InStrRev(f.Name, "."))
End If
End If
Next
msgbox "Done"
ws.Quit
Set ws = Nothing
Set fs = Nothing
Function CleanString(StringToClean)
''http://msdn.microsoft.com/en-us/library/ms974570.aspx
Dim objRegEx
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
''Find anything not a-z, 0-9
objRegEx.Pattern = "[^a-z0-9]"
CleanString = objRegEx.Replace(StringToClean, "")
End Function
Word文档以自定义格式存储,在文件的开头放置一堆二进制文件。
最简单的事情就是在Python中搜索一些东西,搜索以ASCII字符开头的第一行。干得好:
#!/usr/bin/python
import glob
import os
for file in glob.glob("*.doc"):
f = open(file, "rb")
new_name = ""
chars = 0
char = f.read(1)
while char != "":
if 0 < ord(char) < 128:
if ord("a") <= ord(char) <= ord("z") or ord("A") <= ord(char) <= ord("Z") or ord("0") <= ord(char) <= ord("9"):
new_name += char
else:
new_name += "_"
chars += 1
if chars == 100:
new_name = new_name[:20] + ".doc"
print "renaming " + file + " to " + new_name
f.close()
break;
else:
new_name = ""
chars = 0
char = f.read(1)
if new_name != "":
os.rename(file, new_name)
注意:如果你想要多个目录,你需要相应地更改glob线。此外,这不会考虑您尝试重命名的文件是否已经存在,因此如果您有多个具有相同前几个字符的文档,那么您将需要处理它。
我找到了连续100个ASCII字符的第一个块(如果你找不到那个你最终拿起doc关键字等),然后使用前20个来创建新名称,替换任何不是az AZ的东西或带有下划线的0-9以避免文件名问题。