Created
July 3, 2016 16:09
-
-
Save VenkataRaju/e810787bb069452fae0b1ad48ac687c2 to your computer and use it in GitHub Desktop.
File renaming using Nashorn script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var FILE_PATTERNS = /^(Channel_Play_Success_Ratio|Video_Play_Success_Ratio|Login_Success_Ratio|Play_Success_Ratio).+\-1\.csv$/; | |
var Files = java.nio.file.Files; | |
var Paths = java.nio.file.Paths; | |
function printWithCarriageReturn(str) java.lang.System.out['print(String)'](str + '\r'); | |
function throwError(msg) { throw new Error(msg); }; // Brackets are required | |
if (typeof $ARG === 'undefined' || $ARG.length === 0) | |
print("Usage: jjs -scripting renamer.js -- FileOrFolder1 FileOrFolder2 .."); | |
else | |
{ | |
var inputPaths = $ARG.map(function(filePath) Paths.get(filePath)); | |
for (var i = 0; i < inputPaths.length; i++) | |
if (!Files.exists(inputPaths[i])) | |
throw new Error('"' + inputPaths[i] + '" does not exist'); | |
var noOfFilesRenamed = rename(inputPaths, 0); | |
print(noOfFilesRenamed + ' file' + (noOfFilesRenamed === 1 ? '' : 's') + ' renamed.'); | |
} | |
function rename(paths, noOfFilesRenamed) | |
{ | |
for (var i = 0; i < paths.length; i++) | |
{ | |
var source = paths[i]; | |
if (Files.isDirectory(source)) | |
{ | |
var children = Java.from(source.toFile().listFiles() || throwError('Unable to read directory: ' + source)) | |
.map(function(file) file.toPath()); | |
noOfFilesRenamed = rename(children, noOfFilesRenamed); | |
continue; | |
} | |
var fileName = '' + source.fileName; | |
if (!FILE_PATTERNS.test(fileName)) | |
continue; | |
var newName = fileName.substring(0, fileName.length - 6 /* str before -1.csv */) + '.csv'; | |
var dest = source.resolveSibling(newName); | |
Files.move(source, dest); | |
noOfFilesRenamed++; | |
if (noOfFilesRenamed % 300 === 0) | |
printWithCarriageReturn(noOfFilesRenamed); | |
} | |
return noOfFilesRenamed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment