Advertisement
Guest User

Findrepl.bat

a guest
Nov 23rd, 2017
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 36.35 KB | None | 0 0
  1.  
  2.  
  3. @if (@CodeSection == @Batch) @then
  4.  
  5. :: The first line above is...
  6. :: - in Batch: a valid IF command that does nothing.
  7. :: - in JScript: a conditional compilation IF statement that is false,
  8. ::               so this Batch section is omitted until next "at-sign end".
  9.  
  10.  
  11. @echo off
  12.  
  13. rem FindRepl.bat: Utility to search and search/replace strings in a file
  14. rem http://www.dostips.com/forum/viewtopic.php?f=3&t=4697
  15. rem Antonio Perez Ayala
  16.  
  17. rem   - Jun/26/2013: first version.
  18. rem   - Jul/02/2013: use /Q in submatched substrings, use /VR for /V in Replace, eliminate "\r\n" in blocks.
  19. rem   - Jul/07/2013: change /VR by /R, search for "\r\n" with /$ and no /V, /N nor blocks.
  20.  
  21. rem   - Nov/20/2014: Version 2   - New switches: /J, /L, /G, /ARG#, and || separate regexp's in /Alternations.
  22. rem   - Nov/30/2014: Version 2.1 - Changed /ARG# by /VAR. Replacements on numbered-blocks of lines.
  23. rem                                New sets of predefined functions for Date, File, Folder and Drive management.
  24. rem   - Dic/15/2014: Version 2.2 - New "data generating " predefined functions for /S switch combined with /J
  25.  
  26. if "%~1" equ "/?" goto showUsage
  27. if /I "%~1" equ "/help" goto showHelp
  28.  
  29. CScript //nologo //E:JScript "%~F0" %*
  30. if %errorlevel% equ -1 goto showUsage
  31. exit /B %errorlevel%
  32.  
  33. <usage>
  34. Searches for strings in Stdin file, and prints or replaces them.
  35.  
  36. FINDREPL [/I] [/V] [/N] [rSearch] [/E:rEndBlk] [/O:s:e] [/B:rBlock] [/$:1:2...]
  37.          [[/R] [/A] sReplace] [/Q:c] [/S:sSource]
  38.          [/J[:n] [/L:jLast]] [/G:file] [/VAR:name=value,...]
  39.  
  40.   /I         Specifies that the search is not to be case-sensitive.
  41.   /V         Prints only lines that do not contain a match.
  42.   /N         Prints the line number before each line that matches.
  43.   rSearch    Text to be searched for. Also mark the Start of a block of lines.
  44.   /E:rEndBlk Text to be searched for that mark the End of a block of lines.
  45.   /O:s:e     Specifies signed numbers to add to Start/End lines of blocks.
  46.   /B:rBlock  Extra text to be searched for in the blocks of lines.
  47.   /$:1:2...  Specifies to print saved submatched substrings instead of lines.
  48.   sReplace   Text that will replace the matched text.
  49.   /R         Prints only replaced lines.
  50.   /A         Specifies that sReplace has alternative values matching rSearch.
  51.   /Q:c       Specifies a character that is used in place of quotation marks.
  52.   /S:sSource Text to be processed instead of Stdin file.
  53.   /J[:n]     Specifies that sReplace/sSource texts have JScript expressions.
  54.   /L:jLast   Execute jLast as a JScript expression after the last line of file.
  55.   /G:file    Specifies the file to get rSearch and sReplace texts from.
  56.   /VAR:n=v,..Specifies a series of JScript "name=value" var's to initialize.
  57.  
  58. The /Q:c switch allows to use the given character in the search/replacement
  59. texts in the places where quotes are needed, and replace them later.
  60.  
  61. If the first character of any text is an equal-sign, it specifies the name of
  62. a Batch variable that contain the text to be processed.
  63.  
  64. The /J switch specifies that sReplace/sSource texts contain JScript expressions
  65. that are evaluated in order to provide the actual replacement and source texts.
  66.  
  67. All search texts must be given in VBScript regular expression format (regexp).
  68. Matching characters: .=any char, \d=[0-9], \D=non-digit, \w=[A-Za-z0-9_],
  69. \W=non-alphanumeric, \s=[ \t\r\n], \S=non-space. Anchors: ^=begin of line,
  70. $=end of line, \b=begin/end of word. Quantifiers (repeats previous match):
  71. *=zero or more times, +=one or more times, ?=zero or one time. Use parentheses
  72. to delimit these constructs and create "subexpressions". To search for these
  73. special characters, place a back-slash before each one of them: \*+?^$.[]{}()|
  74.  
  75. The /A (alternation) switch allows to define several alternatives separated by
  76. pipe in rSearch/sReplace: "a|b|c" /A "x|y|z" replace a with x, b with y, etc.;
  77. in this case the alternatives can only be case-sensitive literal strings. If /J
  78. switch is added, the alternatives in rSearch are always regular expressions and
  79. in sReplace are JScript expressions, and they must be separated by double
  80. pipes: "red|green|blue||Peter|Paul|Mary" /A "'a color'||'a name'" /J
  81.  
  82.  
  83. The operation performed and the output displayed varies depending on the mix
  84. of parameters and switches given, that can be divided in three general cases.
  85.  
  86. FINDREPL  [/V] [rSearch] [/E:rEndBlk] [/O:s:e] [/B:rBlock]  [[/R] sReplace]
  87.  
  88.  
  89. A) Find-only operation: when sReplace parameter is not given.
  90.  
  91. rSearch                            Show matching lines.
  92. rSearch /V                         Show non-matching lines.
  93. rSearch /O:s:e                     Add S and E to each matching line (block).
  94. rSearch /E:rEndBlk                 From rSearch line(s) to rEndBlk line(s).
  95. rSearch /E:rEndBlk /O:s:e          Add S to rSearch line and E to rEndBlk line.
  96.                                    The last three cases define a "block".
  97. rSearch block /B:rBlock            Search rBlock in the previous block.
  98.  
  99. When rSearch/rEndBlk includes subexpressions, the /$ switch may be added in
  100. order to print only saved submatched substrings instead of complete lines.
  101.  
  102.  
  103. B) Find-Replace operation: when sReplace parameter is added to previous ones.
  104.  
  105. rSearch sReplace                   Show all file lines after replacements.
  106. rSearch sReplace /R                Show only replaced lines.
  107. rSearch block sReplace             Replaces text in blocks only.
  108. rSearch block /B:rBlock sReplace   Replaces only text matched by rBlock.
  109.  
  110. When rSearch/rBlock includes subexpressions, the replacement text may
  111. include $0, $1, ... in order to retrieve saved submatched substrings.
  112.  
  113.  
  114. C) Numbered-block operation: when rSearch parameter is null (requires /O).
  115.  
  116. /O:s:e                             Show block of lines, from line S to line E.
  117. /O:s:e /B:rBlock                   Search rBlock in the previous block.
  118. "" /O:s:e /B:rBlock sReplace       Replaces only text matched by rBlock.
  119.  
  120. In this case if S or E is negative, it specifies counting lines from the end of
  121. file. If E is not given, it defaults to the last line of the file (same as -1).
  122.  
  123.  
  124. The total number of matchings/replacements is returned in ERRORLEVEL.
  125.  
  126.  
  127. </usage>
  128.  
  129. :showUsage
  130. < "%~F0" CScript //nologo //E:JScript "%~F0" "^<usage>" /E:"^</usage>" /O:+1:-1
  131. echo -^> For further help, type: %0 /help
  132. goto :EOF
  133.  
  134. <help>
  135.  
  136. A web site may be opened in order to get further help on the following topics:
  137.  
  138.    1- FindRepl.bat documentation:
  139.          Detailed description of FindRepl features with multiple examples.
  140.  
  141.    2- FindRepl.bat version 2 documentation:
  142.          Additional descriptions on /J, /L, /G switches and || alternatives.
  143.  
  144.    3- Regular Expressions documentation:
  145.          Describe the features that may be used in rSearch, rEndBlk and rBlock.
  146.  
  147.    4- Alternation and Subexpressions documentation:
  148.          Describe how use | to separate values in rSearch with /A switch
  149.          and features of subexpressions for /$ switch and $0..$n in sReplace.
  150.  
  151.    5- JScript expressions documentation (/J switch):
  152.          Describe the operators that may be used in JScript expressions.
  153.  
  154.    6- Data types and functions for JScript expressions.
  155.          Describe additional operations available in JScript:
  156.          - String Object: functions to manipulate strings.
  157.          - Math Object: arithmetic functions.
  158.          - Date Object: functions for date calculations.
  159.          See also Topic 2- Section 3. on predefined functions.
  160.  
  161.    7- FileSystemObject objects documentation:
  162.          Describe the properties that may be used in Property functions
  163.          and the rest of File/Folder/Drive predefined functions.
  164.  
  165.    8- Special folders documentation:
  166.          Describe the values used in specialFolders predefined function.
  167.  
  168.    9- Windows Management Instrumentation FAQ:
  169.          General description about the features and capabilities (classes and
  170.          properties) that may be used in wmiCollection predefined function.
  171.  
  172. </help>
  173.  
  174. :showHelp
  175. setlocal EnableDelayedExpansion
  176. set n=1
  177. set "choices="
  178. for %%a in ("http://www.dostips.com/forum/viewtopic.php\Qf=3&t=4697"
  179.             "http://www.dostips.com/forum/viewtopic.php\Qf=3&t=4697&p=38121#p38121"
  180.             "http://msdn.microsoft.com/en-us/library/6wzad2b2(v=vs.84).aspx"
  181.             "http://msdn.microsoft.com/en-us/library/kstkz771(v=vs.84).aspx"
  182.             "http://msdn.microsoft.com/en-us/library/ce57k8d5(v=vs.84).aspx"
  183.             "http://msdn.microsoft.com/en-us/library/htbw4ywd(v=vs.84).aspx"
  184.             "http://msdn.microsoft.com/en-us/library/bkx696eh(v=vs.84).aspx"
  185.             "http://msdn.microsoft.com/en-us/library/0ea7b5xe(v=vs.84).aspx"
  186.             "http://technet.microsoft.com/en-us/library/ee692772.aspx"
  187.            ) do (
  188.    set "choices=!choices!!n!"
  189.    set "option[!n!]=%%~a"
  190.    set /A n+=1
  191. )
  192. < "%~F0" CScript //nologo //E:JScript "%~F0" "^<help>" /E:"^</help>" /O:+1:-1
  193.  
  194. :getOption
  195. echo/
  196. choice /C %choices%0 /N /M "Select one of previous topics, or press 0 to end:"
  197. if errorlevel %n% goto :EOF
  198. set "choice=%errorlevel%"
  199. explorer "!option[%choice%]:\Q=?!"
  200. echo  - Help on topic %choice% started...
  201. goto getOption
  202.  
  203.  
  204. End of Batch section
  205.  
  206.  
  207. @end
  208.  
  209.  
  210. // JScript section
  211.  
  212.  
  213. // FINDREPL [/I] [/V] [/N] rSearch [/E:rEndBlk] [/O:s:e] [/B:rBlock] [/$:1:2...]
  214. //          [[/R] [/A] sReplace] [/Q:c] [/S:source]
  215. //          [/J[:n] [/L:jEnd]] [/G:file]
  216.  
  217. var options = WScript.Arguments.Named,
  218.     args    = WScript.Arguments.Unnamed,
  219.     env     = WScript.CreateObject("WScript.Shell").Environment("Process"),
  220.     fso     = new ActiveXObject("Scripting.FileSystemObject"), file,
  221.  
  222.     ignoreCase   = options.Exists("I")?"i":"",
  223.     notMatched   = options.Exists("V"),
  224.     showNumber   = options.Exists("N"),
  225.     search       = "",
  226.     endBlk       = undefined,
  227.     offset       = undefined,
  228.     block        = undefined,
  229.     submatches   = undefined,
  230.     justReplaced = options.Exists("R"),
  231.     alternation  = options.Exists("A"),
  232.     replace      = undefined,
  233.     quote        = options.Item("Q"),
  234.     inputLines,
  235.     Jexpr        = options.Exists("J"),
  236.  
  237.     lineNumber = 0, range = new Array(),
  238.     procLines = false, procBlocks = false,
  239.     nextMatch, result  = 0,
  240.  
  241.     match = function ( line, regex ) { return line.search(regex) >= 0; },
  242.  
  243.     parseInts =
  244.        function ( strs ) {
  245.           var Ints = new Array();
  246.           for ( var i = 0; i < strs.length; ++i ) {
  247.              Ints[i] = parseInt(strs[i]);
  248.           }
  249.           return Ints;
  250.        },
  251.  
  252.     getRegExp =
  253.        function ( param, justLoad ) {
  254.           var result = param;
  255.           if ( result.substr(0,1) == "=" ) result = env(result.substr(1));
  256.           if ( quote != undefined ) result = result.replace(eval("/"+quote+"/g"),"\\x22");
  257.           if ( ! justLoad ) result = new RegExp(result,"gm"+ignoreCase);
  258.           return result;
  259.        }
  260.     ; // end var
  261.  
  262.  
  263. // PREDEFINED VARIABLES AND FUNCTIONS
  264.  
  265. if ( Jexpr) {
  266.    JexprN = options.Item("J") ? parseInt(options.Item("J")) : !!
  267.    var SUM = new Array(JexprN+1), N = new Array(JexprN+1), PROD = new Array(JexprN+1),
  268.        MAX = new Array(JexprN+1), MIN = new Array(JexprN+1), n = 0;
  269.    for ( var i = 1; i <= JexprN; i++ ) {
  270.       SUM[i] = 0; N[i] = 0; PROD[i] = 1;
  271.       MAX[i] = Number.NEGATIVE_INFINITY; MIN[i] = Number.POSITIVE_INFINITY;
  272.    }
  273. }
  274.  
  275. // Range functions
  276.  
  277. function choose(arg,i){return(arg[i]);}
  278. function hlookup(arg,lim,a,b) {
  279.    var ind=a;
  280.    for ( var i=a; i<=b; i++ ) if ( arg[i]>arg[ind] && arg[i]<=lim ) ind=i;
  281.    return(ind);
  282. }
  283. function sum(arg,a,b) {
  284.    var val = 0, n = 0, v;
  285.    for ( var i=a; i<=b; i++ ) {
  286.       if ( ! isNaN(v=parseFloat(arg[i])) ) { val+=v; SUM[i]+=v; N[i]++; n++; }
  287.    }
  288.    return(val);
  289. }
  290. function prod(arg,a,b) {
  291.    var val = 1, n = 0, v;
  292.    for ( var i=a; i<=b; i++ ) {
  293.       if ( ! isNaN(v=parseFloat(arg[i])) ) { val*=v; PROD[i]*=v; n++; }
  294.    }
  295.    return(val);
  296. }
  297. function max(arg,a,b) {
  298.    var val=Number.NEGATIVE_INFINITY, v;
  299.    for ( var i=a; i<=b; i++ ) {
  300.       if ( ! isNaN(v=parseFloat(arg[i])) ) {
  301.          if ( v>val ) val=v;
  302.          if ( v>MAX[i] ) MAX[i]=v;
  303.       }
  304.    }
  305.    return(val);
  306. }
  307. function min(arg,a,b) {
  308.    var val=Number.POSITIVE_INFINITY, v;
  309.    for ( var i=a; i<=b; i++ ) {
  310.       if ( ! isNaN(v=parseFloat(arg[i])) ) {
  311.          if ( v<val ) val=v;
  312.          if ( v<MIN[i] ) MIN[i]=v;
  313.       }
  314.    }
  315.    return(val);
  316. }
  317.  
  318. // Date functions
  319.  
  320. file = fso.CreateTextFile("FindRepl.tmp", true);
  321. file.WriteLine( (new Date("12/31/2000")).getVarDate() );  // give proper credit, please...
  322. file.Close();
  323. file = fso.OpenTextFile("FindRepl.tmp", 1);
  324. var date1st = file.Read(2);
  325. file.Close();
  326. file = fso.GetFile("FindRepl.tmp");
  327. file.Delete();
  328.  
  329. function toDate(s) {  // Convert a string or a number (of milliseconds) to Date
  330.    try {
  331.       var d = s.split("/");
  332.       if ( date1st == "31" ) { var aux = d[0]; d[0] = d[1]; d[1] = aux; }  // DD/MM/YYYY
  333.       if ( date1st == "20" ) { aux = d[0]; d[0] = d[1]; d[1] = d[2]; d[2] = aux; }  // YYYY/MM/DD
  334.       d = new Date(d[0]+"/"+d[1]+"/"+d[2]);
  335.    } catch(e) {
  336.       var d = new Date();
  337.       d.setTime(s);
  338.    }
  339.    return(d);
  340. }
  341. function showDate(d,fmt) {  // Show a Date or a number (of milliseconds) with Date formats
  342.    var d2 = d, s = "Unknown date format";
  343.    if ( ! Date.prototype.isPrototypeOf(d2) ) d2 = toDate(d2);
  344.    if ( fmt == 0 || fmt == undefined ) {
  345.       s = d2.toDateString().split(" ");
  346.       s = s[1]+"/"+s[2]+"/"+s[3];
  347.    } else if ( fmt == 1 ) {
  348.       s = d2.toDateString();
  349.    } else if ( fmt == 2 ) {
  350.       s = d2.toString();
  351.    } else if ( fmt == 3 ) {
  352.       s = d2.toString().split(" ");
  353.       s = s[3];
  354.    } else if ( fmt == 4 ) {
  355.       s = d2.toLocaleString().split(" ");
  356.       s = s[s.length-3]+" "+s[s.length-2]+" "+s[s.length-1];
  357.    } else if ( fmt == 5 || fmt == 6 ) {
  358.       d2.setTime(d2.getTime()+d2.getTimezoneOffset()*60000);
  359.       s = d2.toString().split(" ");
  360.       s = s[3]+((fmt==6)?"."+d2.getTime().toString().slice(-3):"");
  361.    } else if ( fmt == 11 ) {
  362.       s = d2.toLocaleDateString();
  363.    } else if ( fmt == 12 ) {
  364.       s = d2.toLocaleString();
  365.    } else {
  366.       var D = (100+d2.getDate()).toString().substr(1),
  367.           M = (101+d2.getMonth()).toString().substr(1),
  368.           Y = d2.getFullYear();
  369.       if ( fmt == 7 ) {
  370.          s = D+"-"+M+"-"+Y;
  371.       } else if ( fmt == 8 ) {
  372.          s = Y+"-"+M+"-"+D;
  373.       } else {
  374.          var t = (d2.toString().split(" "))[3].split(":");
  375.          if ( fmt == 9 ) {
  376.             s = Y+"-"+M+"-"+D+"@"+t.join(".");
  377.          } else if ( fmt == 10 ) {
  378.             s = Y+M+D+t.join("");
  379.          }
  380.       }
  381.    }
  382.    return(s);
  383. }
  384.  
  385. var millisecsPerDay = 1000 * 60 * 60 * 24,
  386.     startTime = new Date(),
  387.     daysNow = Math.floor(startTime.getTime()/millisecsPerDay);
  388. function dateDiff(d1,d2) {
  389.    return( Math.floor((Date.prototype.isPrototypeOf(d1)?d1.getTime():d1)/millisecsPerDay) -
  390.            Math.floor((Date.prototype.isPrototypeOf(d2)?d2.getTime():d2)/millisecsPerDay) );
  391. }
  392. function days(d){return( daysNow - Math.floor((Date.prototype.isPrototypeOf(d)?d.getTime():d)/millisecsPerDay) );}
  393. function dateAdd(d,n) {
  394.    var newD = new Date();
  395.    newD.setTime( (Date.prototype.isPrototypeOf(d)?d.getTime():d) + n*millisecsPerDay );
  396.    return(newD);
  397. }
  398.  
  399. // File, Folder and Drive functions
  400.  
  401. function fileExist(name) {
  402.    return(fso.FileExists(name));
  403. }
  404.  
  405. // === Start of new section added in FindRepl V2.2
  406. function fileCopy(name,destination) {
  407.    fso.CopyFile(name,destination);
  408.    return('File(s) "'+name+'" copied');
  409. }
  410. function fileMove(name,destination) {
  411.    fso.MoveFile(name,destination);
  412.    return('File(s) "'+name+'" moved');
  413. }
  414. function fileDelete(name) {
  415.    fso.DeleteFile(name);
  416.    return('File(s) "'+name+'" deleted');
  417. }
  418.  
  419. var A = "Attributes", TC = "DateCreated", TA = "DateLastAccessed", TW = "DateLastModified",
  420.     D = "Drive", NX = "Name", N = "NameOnly", P = "ParentFolder", F = "Path", SN = "ShortName",
  421.     SF = "ShortPath", Z = "Size", X = "Extension", T = "Type";
  422. function fileProperty(fileName,property) {
  423.    var p,x;
  424.    if ( property == "Extension" ) {
  425.       p = fso.GetExtensionName(fileName);
  426.    } else if ( property == "NameOnly" ) {
  427.       p = fso.GetFile(fileName).Name;
  428.       if ( x=fso.GetExtensionName(fileName) ) p = p.slice(0,-(x.length+1));
  429.    } else {
  430.       p = eval("fso.GetFile(fileName)."+property);
  431.    }
  432.    return(p);
  433. }
  434.  
  435. function folderExist(name) {
  436.    return(fso.FolderExists(name));
  437. }
  438.  
  439. function fileRename(fileName,newName) {
  440.    var file = fso.GetFile(fileName);
  441.    if ( fileName.toUpperCase() == newName.toUpperCase() ) file.Name = "_  .  _";
  442.    file.Name = newName;
  443.    return('File "'+fileName+'" renamed to "'+newName+'"');
  444. }
  445. function folderRename(folderName,newName) {
  446.    var folder = fso.GetFolder(fileName);
  447.    if ( folderName.toUpperCase() == newName.toUpperCase() ) folder.Name = "_  .  _";
  448.    folder.Name = newName;
  449.    return('Folder "'+folderName+'" renamed to "'+newName+'"');
  450. }
  451.  
  452. function Copy(name,destination) {
  453.    fso.GetFile(name).Copy(destination);
  454.    return('File/Folder "'+name+'" copied');
  455. }
  456. function Move(name,destination) {
  457.    fso.GetFile(name).Move(destination);
  458.    return('File/Folder "'+name+'" moved');
  459. }
  460. function Delete(name) {
  461.    fso.GetFile(name).Delete();
  462.    return('File/Folder "'+name+'" deleted');
  463. }
  464.  
  465. function folderCopy(name,destination) {
  466.    fso.CopyFolder(name,destination);
  467.    return('Folder(s) "'+name+'" copied');
  468. }
  469. function folderMove(name,destination) {
  470.    fso.MoveFolder(name,destination);
  471.    return('Folder(s) "'+name+'" moved');
  472. }
  473. function folderDelete(name) {
  474.    fso.DeleteFolder(name);
  475.    return('Folder(s) "'+name+'" deleted');
  476. }
  477.  
  478. function driveProperty(drivePath,property) {
  479.    return( eval("fso.GetDrive(fso.GetDriveName(drivePath))."+property) );
  480. }
  481.  
  482. function folderProperty(folderName,property) {
  483.    var p,x;
  484.    if ( property == "Extension" ) {
  485.       p = fso.GetExtensionName(folderName);
  486.    } else if ( property == "NameOnly" ) {
  487.       p = fso.GetFolder(folderName).Name;
  488.       if ( x=fso.GetExtensionName(fileName) ) p = p.slice(0,-(x.length+1));
  489.    } else {
  490.       p = eval("fso.GetFolder(folderName)."+property);
  491.    }
  492.    return(p);
  493. }
  494.  
  495. // Data generating functions
  496.  
  497. function drivesCollection ( propList ) {
  498.    var e = new Enumerator(fso.Drives), drives = "";
  499.    if ( arguments.length ) {
  500.       for ( ; !e.atEnd(); e.moveNext() ) {
  501.          var drive = e.item();
  502.          for ( var i = 0; i < arguments.length; i++ ) {
  503.             var a = arguments[i];
  504.             drives += (i?",":"")+'"'+(((a=="DriveLetter"||a=="DriveType"||a=="Path")||drive.IsReady)?
  505.                                       eval("drive."+arguments[i]):"Not ready")+'"';
  506.          }
  507.          drives += "\r\n";
  508.       }
  509.    } else {
  510.       for ( ; !e.atEnd(); e.moveNext() ) {
  511.          drives += '"'+e.item().Path+'"\r\n';
  512.       }
  513.    }
  514.    return(drives);
  515. }
  516.  
  517. function filesCollection ( pathOrCol, propList ) {
  518.    var files = "", fc;
  519.    if ( arguments.length ) {
  520.       try {  // if ( pathOrCol is path ) {
  521.          fc = fso.GetFolder(pathOrCol).Files;
  522.       } catch (e) {  // } else {  // pathOrCol is filesCol
  523.          fc = pathOrCol;
  524.       }
  525.       for ( fc = new Enumerator(fc); !fc.atEnd(); fc.moveNext() ) {
  526.          var file = fc.item();
  527.          for ( var i = 1; i < arguments.length; i++ ) {
  528.             files += (i>1?",":"")+'"'+eval("file."+arguments[i])+'"';
  529.          }
  530.          files += "\r\n";
  531.       }
  532.    } else {
  533.       for ( fc = new Enumerator(fso.GetFolder(".").Files); !fc.atEnd(); fc.moveNext() ) {
  534.          files += '"'+fc.item().Name+'"\r\n';
  535.       }
  536.    }
  537.    return(files);
  538. }
  539.  
  540. function foldersCollection ( pathOrCol, propList ) {
  541.    var folders = "", fc;
  542.    if ( arguments.length ) {
  543.       try {  // if ( pathOrCol is path ) {
  544.          fc = fso.GetFolder(pathOrCol).SubFolders;
  545.       } catch (e) {  // } else {  // pathOrCol is foldersCol
  546.          fc = pathOrCol;
  547.       }
  548.       for ( fc = new Enumerator(fc); !fc.atEnd(); fc.moveNext() ) {
  549.          var folder = fc.item();
  550.          for ( var i = 1; i < arguments.length; i++ ) {
  551.             if ( arguments[i].indexOf(".SubFolders") >= 0 ) {
  552.                if ( folder.SubFolders && eval(arguments[i]) ) {
  553.                   arguments[0] = folder.SubFolders;
  554.                   folders += (folders.slice(-2)!="\r\n"?"\r\n":"") + foldersCollection.apply(undefined,arguments);
  555.                   if ( i+1 < arguments.length ) eval(arguments[i+1]);
  556.                }
  557.                i = arguments.length;
  558.             } else if ( arguments[i].indexOf(".Files") >= 0 ) {
  559.                folders += (folders.slice(-2)!="\r\n"?"\r\n":"") + eval(arguments[i]);
  560.             } else {
  561.                folders += (i>1?",":"")+'"'+eval("folder."+arguments[i])+'"';
  562.             }
  563.          }
  564.          if ( folders.slice(-2) != "\r\n" ) folders += "\r\n";
  565.       }
  566.    } else {
  567.       for ( fc = new Enumerator(fso.GetFolder(".").SubFolders); !fc.atEnd(); fc.moveNext() ) {
  568.          folders += '"'+fc.item().Name+'"\r\n';
  569.       }
  570.    }
  571.    return(folders);
  572. }
  573.  
  574. function specialFolders ( specialFolder, propList ) {
  575.    var WshShell = WScript.CreateObject("WScript.Shell"), special = "", fc;
  576.    if ( arguments.length ) {
  577.       var fc = specialFolder.split("."), folder = WshShell.SpecialFolders(fc[0]);
  578.       for ( fc = new Enumerator(eval("fso.GetFolder(folder)."+fc[1])); !fc.atEnd(); fc.moveNext() ) {
  579.          var s = fc.item();
  580.          for ( var i = 1; i < arguments.length; i++ ) {
  581.             special += (i>1?",":"")+'"'+eval("s."+arguments[i])+'"';
  582.          }
  583.          special += "\r\n";
  584.       }
  585.    } else {
  586.       for ( fc = new Enumerator(WshShell.SpecialFolders); !fc.atEnd(); fc.moveNext() ) {
  587.          special += fc.item()+"\r\n";
  588.       }
  589.    }
  590.    return(special);
  591. }
  592.  
  593. function wmiCollection ( className, propList ) {
  594.    // http://msdn.microsoft.com/en-us/library/aa393741(v=vs.85).aspx
  595.    var wmi = "", colItems;
  596.    if ( arguments.length > 1 ) {
  597.       // http://msdn.microsoft.com/en-us/library/windows/desktop/aa394606(v=vs.85).aspx
  598.       colItems = GetObject("WinMgmts:").ExecQuery("Select * from " + className);
  599.       for ( var e = new Enumerator(colItems); ! e.atEnd(); e.moveNext() ) {
  600.          var s = e.item();
  601.          for ( var i = 1; i < arguments.length; i++ ) {
  602.             wmi += (i>1?",":"")+'"'+eval("s."+arguments[i])+'"';
  603.          }
  604.          wmi += "\r\n";
  605.       }
  606.    } else if ( arguments.length == 1 ) {
  607.       // Method suggested by: http://msdn.microsoft.com/en-us/library/aa392315(v=vs.85).aspx
  608.       //                      https://gallery.technet.microsoft.com/f0666124-3b67-4254-8ff1-3b75ae15776d
  609.       colItems = GetObject("WinMgmts:").Get(className).Properties_;
  610.       for ( var e = new Enumerator(colItems); ! e.atEnd(); e.moveNext() ) {
  611.          wmi += e.item().Name+"\r\n";
  612.       }
  613.    } else {
  614.       // https://gallery.technet.microsoft.com/scriptcenter/5649568b-074e-4f5d-be52-e8b7d8fe4517
  615.       colItems = GetObject("WinMgmts:");  // imply ("WinMgmts:\root\cimv2")
  616.       for ( var e = new Enumerator(colItems.SubclassesOf()); ! e.atEnd(); e.moveNext() ) {
  617.          wmi += e.item().Path_.Class+"\r\n";
  618.       }
  619.    }
  620.    return(wmi);
  621. }
  622.  
  623. // === End of new section added in FindRepl V2.2
  624. // Other functions
  625.  
  626. function prompt(s){WScript.Stderr.Write(s); return(keyb.ReadLine());}
  627. function FOR($,init,test,inc,body) {
  628.    var For="";
  629.    for ( eval(init); eval(test); eval(inc) ) For+=eval(body);
  630.    return(For);
  631. }
  632. var arguments="";
  633.  
  634.  
  635. // PROCESS PARAMETERS
  636.  
  637. if ( file=options.Item("G") ) {
  638.    file = fso.OpenTextFile(file, 1);
  639.    search = "";
  640.    if ( alternation ) replace = "";
  641.    var sepIn = Jexpr?/(\\\\|\\\||[^\|]|[^\|][^\|])+/g:/(\\\\|\\\||[^\|])+/g, sepOut = "";
  642.    while ( ! file.AtEndOfStream ) {
  643.       if ( block=file.ReadLine() ) {
  644.          if ( block.substr(0,4) == "var " && Jexpr ) {
  645.             eval ( block );
  646.          } else if ( block.substr(0,2) != "//" ) {
  647.             if ( block.slice(0,1)+block.slice(-1) == '""' ) block = block.slice(1,-1);
  648.             block = block.match(sepIn);
  649.             search += sepOut+block[0];
  650.             if ( alternation ) replace += sepOut+(block[1]?block[1]:"");
  651.             sepOut = Jexpr?"||":"|";
  652.          }
  653.       }
  654.    }
  655.    file.Close();
  656.    if ( quote != undefined ) search = search.replace(eval("/"+quote+"/g"),"\\x22");
  657. } else {  // No option /G given
  658.    if ( args.length > 0 ) {
  659.       search = getRegExp(args.Item(0),true);
  660.    }
  661.    if ( args.length > 1 ) {
  662.       replace = args.Item(1);
  663.       if ( replace.substr(0,1) == "=" ) replace = env(replace.substr(1));
  664.    }
  665. }
  666. if ( replace ) {
  667.    if ( quote != undefined ) replace = replace.replace(eval("/"+quote+"/g"),"\\x22");
  668. }
  669.  
  670. if ( ! WScript.Arguments.length ) WScript.Quit(-1);
  671.  
  672. if ( options.Exists("E") ) {
  673.    endBlk = getRegExp(options.Item("E"));
  674.    procBlocks = true;
  675. }
  676. if ( options.Exists("O") ) {
  677.    offset = parseInts(options.Item("O").split(":"));
  678.    procBlocks = true;
  679. }
  680. block = undefined;
  681. if ( options.Exists("B") ) {
  682.    block = getRegExp(options.Item("B"),true);
  683. }
  684. if ( options.Exists("$") ) submatches = parseInts(options.Item("$").split(":"));
  685. var removeCRLF = false;
  686.  
  687.  
  688. if ( replace != undefined ) {
  689.    removeCRLF = (block == "\\r\\n") && (replace == "");
  690.  
  691.    if ( alternation ) {  // Enable alternation replacements from "Se|ar|ch" to "Re|pla|ce"
  692.       if ( ! Jexpr ) {  // Original version
  693.  
  694.          var searchA = search.match(/(\\\\|\\\||[^\|])+/g),
  695.              replaceA = replace.match(/(\\\\|\\\||[^\|])+/g),
  696.              repl = new Array();
  697.          for ( var i = 0; i < searchA.length; i++ ) {
  698.             repl[eval('"'+searchA[i]+'"')] = replaceA?replaceA[i]?eval('"'+replaceA[i]+'"'):"":"";
  699.          }
  700.          replace = function($0,$1,$2) { return repl[$0]; };
  701.          searchA.length = 0;
  702.          if ( replaceA ) replaceA.length = 0;
  703.  
  704.       } else {  // Version 2: Search alternation have regular expressions:  "regexp1||regexp2||regexp3"
  705.                 //            Replace alternation have JScript expressions: "'Re'||'pla'||'ce'"
  706.  
  707.          var searchA = search.match(/(\\\\|\\\||[^\|]|[^\|][^\|])+/g), // divide search "regexp1||regexp2" in parts
  708.              repl = replace.match(/(\\\\|\\\||[^\|]|[^\|][^\|])+/g);   // the same for "replace1||replace2"
  709.  
  710.          search = "";
  711.          replace = "$0,";                               // "function($0,"
  712.          for ( var i = 0; i < searchA.length; i++ ) {   // process each regexpI
  713.             search += (i?'|':'')+'('+searchA[i]+')';    // re-assemble search regexp as "(regexp1)|(regexp2)"
  714.             var subexprs = searchA[i].match(/[^\\]?\(/g);// count subexpressions in this regexpI
  715.             subexprs = subexprs?subexprs.length:0;      // zero if no one
  716.             for ( var j = 0; j <= subexprs; j++ ) {     // insert each subexpression
  717.                   replace += '$'+(i+1)+'$'+j+',';       // 'function($0,' + "$i$0,$i$j,..."
  718.             }
  719.             repl[i] = repl[i].replace(/\$(\d{1,2})/g,"$$"+(i+1)+"$$$1");        // change "$n" by "$i$n" in replaceI
  720.          }
  721.  
  722.          replace += "$offset,$string";                  // 'function($0, $i$0,$i$1,$i$2, ...' + "$offset, $string)"
  723.          eval ("replace=function("+replace+"){for (var i=1; !eval('$'+i+'$0'); i++);return(eval(repl[i-1]));};");
  724.  
  725.          Jexpr = false;                                 // the replace function already includes the "eval" part
  726.  
  727.          searchA = undefined;
  728.          if ( subexprs ) subexprs = undefined;
  729.  
  730.       }
  731.  
  732.    } else {  // No alternation
  733.  
  734.       var evalReplace = "";
  735.       if ( Jexpr) {
  736.          for ( var i = 0; i <= JexprN; i++ ) evalReplace += (i?',':'')+'$'+i;
  737.          eval ( "evalReplace = function("+evalReplace+") { return(eval(replace)); };" );
  738.       }
  739.  
  740.    }
  741.  
  742. } else {  // replace == undefined: Find-only operation (to do: adjust values of /$ switch)
  743.  
  744.    if ( Jexpr ) {  // Find a "second-level" alternation
  745.       var searchA = search.split("||");                 // divide search "regexp1||regexp2" in parts
  746.       search = "";
  747.       for ( var i = 0; i < searchA.length; i++ ) {
  748.          search += (i?'|':'')+'('+searchA[i]+')';       // re-assemble search regexp as "(regexp1)|(regexp2)"
  749.       }
  750.       searchA = undefined;
  751.    }
  752.  
  753. }
  754.  
  755. if ( block=options.Item("VAR") ) eval ( "var "+block+";" );
  756. if ( search != "" ) search = new RegExp(search, "gm"+ignoreCase);
  757. if ( block  != undefined ) block  = new RegExp(block , "gm"+ignoreCase);
  758. var keyb = fso.OpenTextFile("CONIN$", 1);
  759.  
  760.  
  761. // PROCESS INPUT FILE
  762.  
  763.  
  764. // FINDREPL [/I] [/V] [/N] rSearch [/E:rEndBlk] [/O:s:e] [/B:rBlock] [/$:s1...]
  765. //          [[/R] [/A] sReplace] [/Q:c] [/S:sSource]
  766.  
  767. //          In Search and Replace operations:
  768. //            /V or /N switches implies line processing
  769. //            /E or /O switches implies block (and line) processing
  770. //          If Search operation (with no previous switches) have NOT /$ switch:
  771. //            implies line processing (otherwise is file processing)
  772.  
  773. var severalLines = false;
  774. if ( options.Exists("S") ) {  // Process Source string instead of file
  775.    var source = options.Item("S");
  776.    if ( source.substr(0,1) == "=" ) source = env(source.substr(1));
  777.    if ( ! Jexpr ) {
  778.       inputLines = new Array(); lastLine = 1;
  779.       inputLines[0] = source;
  780.       procLines = true;
  781.    } else {
  782.       inputLines = eval(source);
  783.       severalLines = true;
  784.    }
  785. } else {  // Process Stdin file
  786.    inputLines = WScript.StdIn.ReadAll();
  787.    severalLines = true;
  788. }
  789.  
  790. if ( severalLines ) {
  791.  
  792.    if ( notMatched || showNumber || procBlocks ) procLines = true;
  793.    if ( replace==undefined && submatches==undefined ) procLines = true;
  794.  
  795.    if ( procLines ) {  // Separate file contents in lines
  796.       var lastByte = inputLines.slice(-1);
  797.       inputLines = inputLines.replace(/([^\r\n]*)\r?\n/g,"$1\n").match(/^.*$/gm);
  798.       lastLine = inputLines.length - ((lastByte == "\n")?1:0);
  799.    }
  800.  
  801.    if ( procBlocks ) {  // Create blocks of lines
  802.       if ( search != "" ) {  // Blocks based on Search lines:
  803.          if ( offset == undefined ) offset = new Array(0,0);
  804.          for ( var i = 1; i <= lastLine; i++ ) {
  805.             if ( match(inputLines[i-1],search) ) {
  806.                if ( endBlk != undefined ) {  // 1- from Search line to EndBlk line [+offsets].
  807.                   for ( var j=i+1; j<=lastLine && !match(inputLines[j-1],endBlk); j++ );
  808.                   if ( j <= lastLine ) {
  809.                      var s = i+offset[0], e = j+offset[1];
  810.                      // Insert additional code here to cancel overlapped blocks
  811.                      range.push(s>0?s:1, e>0?e:1);
  812.                   }
  813.                   i = j;
  814.                } else {  // 2- surrounding Search lines with offsets.
  815.                   s = i+offset[0], e = i+offset[1];
  816.                   range.push(s>0?s:1, e>0?e:1);
  817.                }
  818.             }
  819.          }
  820.       } else {  // Offset with no Search: block is range of lines
  821.          if ( offset.length < 2 ) offset[1] = lastLine;
  822.          s = offset[0]<0 ? offset[0]+lastLine+1 : !!
  823.          e = offset[1]<0 ? offset[1]+lastLine+1 : !!
  824.          range.push(s>0?s:1, e>0?e:1);
  825.       }
  826.       if ( range.length == 0 ) WScript.Quit(0);
  827.       range.push(0xFFFFFFFF,0xFFFFFFFF);
  828.    }
  829.  
  830. }
  831. // endif severalLines
  832.  
  833. if ( replace == undefined ) {  // Search operations
  834.    if ( procLines ) {  // Search on lines
  835.       if ( procBlocks ) {  // Process previously created blocks
  836.          for ( var r=0, lineNumber=1; lineNumber <= lastLine; lineNumber++ ) {
  837.             if ( (range[r]<=lineNumber && lineNumber<=range[r+1]) != notMatched ) {
  838.                if ( submatches != undefined ) {
  839.                   if ( showNumber ) WScript.Stdout.Write(lineNumber+":");
  840.                   while ( (nextMatch = block.exec(inputLines[lineNumber-1])) != null ) {
  841.                      for ( var s = 0; s < submatches.length; s++ ) {
  842.                         WScript.Stdout.Write(" " + (quote!=undefined?quote:'"') +
  843.                                                    nextMatch[submatches[s]] +
  844.                                                    (quote!=undefined?quote:'"'));
  845.                      }
  846.                      result++;
  847.                   }
  848.                   WScript.Stdout.WriteLine();
  849.                } else {
  850.                   if ( block == undefined  ||  match(inputLines[lineNumber-1],block) ) {
  851.                      if ( showNumber ) WScript.Stdout.Write(lineNumber+":");
  852.                      WScript.Stdout.WriteLine(inputLines[lineNumber-1]);
  853.                      result++;
  854.                   }
  855.                }
  856.             }
  857.             if ( lineNumber >= range[r+1] ) r += 2;
  858.          }
  859.       } else {  // Process all lines for Search
  860.          for ( lineNumber = 1; lineNumber <= lastLine; lineNumber++ ) {
  861.             if ( match(inputLines[lineNumber-1],search) != notMatched ) {
  862.                if ( showNumber ) WScript.Stdout.Write(lineNumber+":");
  863.                if ( submatches != undefined ) {
  864.                   search.lastIndex = 0;
  865.                   while ( (nextMatch = search.exec(inputLines[lineNumber-1])) != null ) {
  866.                      for ( var s = 0; s < submatches.length; s++ ) {
  867.                         WScript.Stdout.Write(" " + (quote!=undefined?quote:'"') +
  868.                                                    nextMatch[submatches[s]] +
  869.                                                    (quote!=undefined?quote:'"'));
  870.                      }
  871.                      result++;
  872.                   }
  873.                   WScript.Stdout.WriteLine();
  874.                } else {
  875.                   WScript.Stdout.WriteLine(inputLines[lineNumber-1]);
  876.                   result++;
  877.                }
  878.             }
  879.          }
  880.       }
  881.  
  882.    } else {  // Search on entire file and show submatched substrings
  883.       if ( submatches != undefined ) {
  884.          while ( (nextMatch = search.exec(inputLines)) != null ) {
  885.             for ( var s = 0; s < submatches.length; s++ ) {
  886.                WScript.Stdout.Write(" " + (quote!=undefined?quote:'"') +
  887.                                           nextMatch[submatches[s]] +
  888.                                           (quote!=undefined?quote:'"'));
  889.             }
  890.             result++;
  891.             WScript.Stdout.WriteLine();
  892.          }
  893.       }
  894.    }
  895.  
  896. } else {  // Replace operations
  897.  
  898.    if ( procLines ) {  // Replace on lines
  899.       if ( procBlocks ) {  // Process previously created blocks
  900.          if ( block == undefined ) block = search;  // Replace rSearch or rBlock (the last one)
  901.          var CRLFremoved = false;
  902.          for ( var r=0, lineNumber=1; lineNumber <= lastLine; lineNumber++ ) {
  903.             if ( range[r]<=lineNumber && lineNumber<=range[r+1] ) {
  904.                if ( removeCRLF ) {
  905.                   WScript.Stdout.Write(inputLines[lineNumber-1]);
  906.                   CRLFremoved = true;
  907.                   result++;
  908.                } else {
  909.                   if ( match(inputLines[lineNumber-1],block) ) {
  910.                      if ( CRLFremoved ) { WScript.Stdout.WriteLine(); CRLFremoved = false; }
  911.                      WScript.Stdout.WriteLine(inputLines[lineNumber-1].replace(block,Jexpr?evalReplace:replace));
  912.                      result++;
  913.                   } else {
  914.                      if ( CRLFremoved ) { WScript.Stdout.WriteLine(); CRLFremoved = false; }
  915.                      if ( ! justReplaced ) WScript.Stdout.WriteLine(inputLines[lineNumber-1]);
  916.                   }
  917.                }
  918.             } else {
  919.                if ( CRLFremoved ) { WScript.Stdout.WriteLine(); CRLFremoved = false; }
  920.                if ( ! justReplaced ) WScript.Stdout.WriteLine(inputLines[lineNumber-1]);
  921.             }
  922.             if ( lineNumber >= range[r+1] ) r += 2;
  923.          }
  924.          if ( CRLFremoved ) { WScript.Stdout.WriteLine(); CRLFremoved = false; }
  925.       } else {  // Process all lines for Replace
  926.          for ( lineNumber = 1; lineNumber <= lastLine; lineNumber++ ) {
  927.             if ( match(inputLines[lineNumber-1],search) ) {
  928.                WScript.Stdout.WriteLine(inputLines[lineNumber-1].replace(search,Jexpr?evalReplace:replace));
  929.                result++;
  930.             } else {
  931.                if ( ! justReplaced ) WScript.Stdout.WriteLine(inputLines[lineNumber-1]);
  932.             }
  933.          }
  934.       }
  935.  
  936.    } else {  // Replace on entire file
  937.       WScript.Stdout.Write(inputLines.replace(search,Jexpr?evalReplace:replace));
  938.    }
  939.  
  940. }
  941.  
  942. if ( Jexpr && (lastLine=options.Item("L")) ) {
  943.    if ( lastLine.substr(0,1) == '=' ) lastLine = env(lastLine.substr(1));
  944.    if ( quote != undefined ) lastLine = lastLine.replace(eval("/"+quote+"/g"),"\\x22");
  945.    WScript.Stdout.WriteLine( eval(lastLine) );
  946. }
  947.  
  948. WScript.Quit(result);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement