编程是在学习中不断进步,这个不假,这两天一直在折腾VB脚本编程,原因可以追溯到我关于VB脚本编程的第一篇文章简单的VB小脚本之——文件处理脚本,里面提到了上帝,额不,是我的客户提到的一个简单的小要求,就是希望我写个VB的脚本来处理文件,于是我就现学现用了,完成了1.0的版本。客户就是上帝,上帝说要写VB脚本,于是就有了VB脚本。这不,提交了之后,上帝说,改进一下,在命令行里实现调用,并且传参数,比如,xx.vbs -normal 22.log 66 Eric.Tang这个用来把22.log文件中的“66”字符串儿替换为“Eric.Tang”,同时呢还要加入正则表达式的验证,比如xx.vbs -regex 22.log “<.*>" Eric.Tang这个用来把22.log文件中<>括号中的内容替换为Eric.Tang,折腾了大半天之后就有了以下的VB脚本2.0版本,内容源码如下:
currentPath=CreateObject("Scripting.FileSystemObject").GetFolder(".").Path
Set objArgs = WScript.Arguments
If objArgs.count < 4 Then
Msgbox("Missing parameters!")
Else
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(currentPath & "\" & objArgs(1)) Then 'if file exists or not
Set objFile=objFSO.OpenTextFile(currentPath & "\" & objArgs(1))
str=objFile.ReadAll 'get content of the file
objFile.close
If objArgs(0) = "-normal" Then
oldStr=objArgs(2) 'the old string that you want to find
newStr=objArgs(3) 'the new string that you want to replace with
If oldStr <> "" Then
str=replace(str,oldStr,newStr)
tmpArray=split(objArgs(1),".")
Set newFile=objFSO.CreateTextFile(currentPath & "\" & tmpArray(0) & "_Normal" & ".txt")
newFile.write(str)
newFile.close
If objFSO.FileExists(currentPath & "\" & tmpArray(0) & "_Normal" & ".txt") Then
Msgbox("Normal handled file has been created successfully! Please check " & currentPath & "\" & tmpArray(0) & "_Normal" & ".txt")
Else
Msgbox("Errors happened while Normal-Handling!")
End If
End If
ElseIf objArgs(0) = "-regex" Then
Set regEx=New RegExp 'create a regex
patern=objArgs(2)
regEx.Pattern=patern
regEx.IgnoreCase = True 'ingnore the Upper/Lower case
regEx.Global = True 'if can be used Globally
If str <> "" Then
Set Matches = regEx.Execute(str) 'excute search
If Matches.count <> 0 Then
For Each Match in Matches
str=replace(str,Match.Value,objArgs(3))
Next
tmpArray=split(objArgs(1),".")
Set newFile=objFSO.CreateTextFile(currentPath & "\" & tmpArray(0) & "_Regex" & ".txt")
newFile.write(str)
newFile.close
If objFSO.FileExists(currentPath & "\" & tmpArray(0) & "_Regex" & ".txt") Then
Msgbox("Regex handled file has been created successfully! Please check " & currentPath & "\" & tmpArray(0) & "_Regex" & ".txt")
Else
Msgbox("Errors happened while Regex-Handling!")
End If
Else
Msgbox("No matches found!")
End If
End If
End If
Else
Msgbox("File not exist!")
End If
End If
因为我是初次接触VB脚本,写的一般,仅仅是能完成要求的功能而已,可扩展性什么的就几乎没什么考虑的,所以在我看来,程序猿可能会在职业生涯中临时要去学很多东西,虽然不是你感兴趣的东西,但工作所需,我们都可能要及时学习并运用,在学习中前进,在学习中进步。