DonationCoder.com Software > Coding Snack Guidelines
rename files according to a list - not the usual rename - please read on!
Krishean:
--- Code: Javascript ---function exit(a){return WScript.Quit(a);}function echo(a){return WScript.Echo(a);} var fso=WScript.CreateObject('Scripting.FileSystemObject'); exit(main());function main(){ var tmp=[]; // read list if(fso.FileExists('list.txt')){ try{ var list=safe_split(file_get_contents('list.txt')); }catch(err){ // there was an error while reading list.txt echo('Error: Unable to read list.txt!'); return 1; } // parse list var rExp=/^(\d+)\s+([ \w\d]+)$/i; var line=1; for(var i=0;i<list.length;i++){ list[i]=trim(list[i]); // trim off excess whitespace from beginning and end of lines if(list[i]=='')continue; // don't process blank lines if(rExp.test(list[i])){ var obj=rExp.exec(list[i]); if(String(obj[1]).length<2)obj[1]='0'+obj[1]; tmp.push([obj[1],obj[2]]); }else{ echo('Error: Unable to parse line '+line+' of list.txt'); return 1; } line++; } list=tmp; tmp=[]; // read directory var e=new Enumerator(fso.GetFolder('.').Files); for(;!e.atEnd();e.moveNext()){ var fname=e.item().Name.toLowerCase(); // don't attempt to rename itself, or list.txt if(e.item() == WScript.ScriptFullName || fname == 'list.txt')continue; for(var j=0;j<list.length;j++){ // compare filename if(fname.indexOf(list[j][1].toLowerCase())!=-1){ // create the new filename var newname=list[j][0]+' - '+list[j][1]+'.'+ fso.GetExtensionName(e.item()); tmp.push('"'+e.item().Name+'" => "'+newname+'"'); // rename file e.item().Name=newname; break; } } } }else{ // the script wasn't able to find a list.txt file in the current directory echo('Error: Does list.txt exist in the current directory?'); return 1; } // output a message saying whether files were renamed or not echo(tmp.length>0?'Files that were renamed:\n\t'+ tmp.join('\n\t'):'No files were renamed!'); return 0;} function safe_split(s){return s.replace(/\r\n/g,'\n').replace(/\r/g,'\n').split('\n');}function trim(s){return s.replace(/^\s+/,'').replace(/\s+$/,'');} function file_get_contents(filename){ var ptr=fso.OpenTextFile(filename,1,false); var str=new String(ptr.ReadAll()); ptr.Close(); return str;}
line 25 adds one leading zero if there are less than two characters in the number
i can also have it strip characters other than letters/numbers/spaces, but that may have unforseen effects
Navigation
[0] Message Index
[*] Previous page
Go to full version