看到有人用Dos命令写,看了看For指令头晕。于是用WSH脚本写一个,忙活完了发现不支持UTF-8。
WSH的FSO只支持ANSI,UTF-16,ASCII三种编码...
下面是代码了,保存为.wsf后缀双击运行。extensionReg是文件后缀的正则表达式,replacePair是替换规则。
replacePair可以包含多个替换,每个替换是一个数组元素,也是一个对象,此对象reg属性是匹配规则,str属性是要替换的字条串。
<job id="main">
<script language="JScript">
// Note: This script will not function correctly with non-ANSI Encoding files.
// ################################ Settings ####################### /
// File's extension
var extensionReg = /^.+\.(xml|txt)$/ig;
// Replace rules
// The replacePair Array contains multiple replacement rule objects.
// Each object contains reg and str property.
// The reg property is a Regular Expression
// and the str property replaces every successful match of reg.
var replacePair = [{reg:/\<VALUE\>[^<>]*\<\/value\>/ig, str:"###value###"},
{reg:/\<LABEL\>[^<>]*\<\/label\>/ig, str:"###label###"}];
// ####################################################################### /
// Constant
var WshShell = WScript.CreateObject("WScript.Shell");
var ForReading = 1, ForWriting = 2, ForAppending = 8;
var ANSI = -2, UTF-16 = -1, ASCII = 0;
var fso = new ActiveXObject("Scripting.FileSystemObject");
// Current Folder
var curFolder = fso.GetFolder(WshShell.CurrentDirectory);
// iterator of Files in the current folder
var fc = new Enumerator(curFolder.files);
var counter = 0;
// loop though files
for (; !fc.atEnd(); fc.moveNext())
{
var file = fc.item();
var filefileName = file.Name;
// test of file name match
if (fileName.search(extensionReg) == -1)
continue;
var content = readAllFromFile(file.Path);
var contentcontentRet = content;
var pc = new Enumerator(replacePair);
for (; !pc.atEnd(); pc.moveNext()) {
var replaceItem = pc.item();
contentRetcontentRet = contentRet.replace(replaceItem.reg, replaceItem.str);
}
if (contentRet != content) {
writeStrToFile(file.Path, contentRet);
++counter;
}
}
// Show the result with OK button and "Information Mark" icon.
WshShell.Popup(counter + " files has been replaced.", 0, "Result", 0 + 64);
function readAllFromFile(path) {
var ret = "";
var ts = fso.OpenTextFile(path, ForReading, false, ANSI);
if (!ts.AtEndOfStream)
ret = ts.ReadAll();
ts.Close();
return ret;
}
function writeStrToFile(path, str) {
var ts = fso.OpenTextFile(path, ForWriting, true, ANSI);
ts.Write(str);
ts.Close();
}
// Debug
function trace(msg) {
WScript.Echo(msg);
WScript.Quit();
}
</script>
</job>