How To - Use Replace In Files with regex to add file path & name

How To - Use Replace In Files with regex to add file path & name

24
Basic UserBasic User
24

    Oct 11, 2010#1

    GOAL: To locate within a specified folder/share and within files that have a file name pattern, 2 lines of text that in which line 1 begins with 2 '/' characters (i.e. //TextToFind ) and is followed by 1 word and then 1 or more spaces and then on line 2 begins with 0 to many spaces followed by a key word and then replace the text on line 2 with itself plus the file name & path, the current date and a fixed piece of text.

    In order to keep this as non-verbose as possible I decided the best and easiest way to articulate what I am trying to do is to give a specific example.

    The directory I will be searching in and the name of a file I would want to edit within that directory are listed below:

    FILE NAME: rs_This_Is_My_Report.txt
    FILE LOCATION/PATH: \\MyFileShare\MyFiles\

    Within this file there is the following 3 lines of text and these 3 lines are not the first 3 lines in the file.

    NOTE: In the CODE sections below the TABLE_A & TABLE_B text are supposed to be aligned but for some reason they don't appear that way in the below CODE boxes and I did use spaces only and no tabs so don't let that throw you. The number of spaces on in line 3 below are 9.

    Code: Select all

    //SELECT 
      SELECT TABLE_A.Column1 AS 'MyColumn_01',
             TABLE_B.ColumnX AS 'MyColumnX',
    I want to edit this second line of text so that everything after the word "SELECT" is pushed down to a new line (not just added to what is already in the following line in this file) and also add to line 2 a string of text that consists of both fixed text and some dynamic text like the name of the file being edited.

    This is what the edited lines should look like after the 'Replace In Files' is complete:

    Code: Select all

    //SELECT 
      SELECT /*XXXXX;FilePath=\\MyFileShare\MyFiles\;FileName=rs_This_Is_My_Report.txt;Date=2010/10/01;Area=Main;*/
             TABLE_A.Column1 AS 'MyColumn_01',
             TABLE_B.ColumnX AS 'MyColumnX',
    In this example the string of text is a comment as delimited by the "/*" and "*/ " which are used in the T-SQL language to indicate commented text. Within this string of text I have added several Name/Value pairs in which some of the values are fixed like the date and some are dynamic like the file name. The file path can be fixed because I will be searching in only 1 directory, but I am searching thru hundreds of files and so the FileName will need to be dynamic.

    My end goal is to add to several hundred txt files this string of text consisting of Name/Value pairs and not do it manually 1 file at a time. I'm OK with using the START button in the REPALCE IN FILES function (as opposed to REPLACE ALL) and verify each replace in each file; I just don't want to have to manually add the text with as many files as I need to edit.

    I also need to point out that a file may have more then one instance of a line of text that matches this pattern and that’s OK. If there is a file with more than one matching line then replacing all instances of the line in a file is what I want.

    I hope I have explained this properly and that someone (probably Mofi) will have some suggestions on how to do this if it is in fact possible. I have posted this in the UE section because the UEStudio has no REPLACE/REGEX forum and because if this is doable it could be of benefit to others who use UE and not just users of UEStudio.

    Please don't hesitate to ask any questions and I look forward to your comments.

    Thanks

    6,603548
    Grand MasterGrand Master
    6,603548

      Oct 11, 2010#2

      The command Replace in Files can't do that. Here is a script which should do what you want. You need to copy some functions I wrote into the script file before you can execute it. The missing functions are:

      GetListOfFiles
      GetFileIndex (point 6)
      GetFilePath and GetNameOfFile from the FileNameFunctions.

      You need only the code of the functions included in the script file, not the explanation comment above and the demonstration code below.

      Code: Select all

      var g_nDebugMessage=1;  // Enable debug messages to output window.
      
      if (GetListOfFiles (0, "\\\\MyFileShare\\MyFiles\\", "*.txt", false)) {
      
         var sFileName = "";
         var sFilePath = "";
         var sFullName = "";
         var nActiveDocIndex = 0;
      
         // Get file index of list file (= active file).   
         var nListFile = GetFileIndex();
      
         // Get current date/time and build date string in required format.
         var oCurDate = new Date();
         var nDateVal = oCurDate.getFullYear();
         var sCurDate = nDateVal.toString() + '/';
         nDateVal = oCurDate.getMonth() + 1;
         if (nDateVal < 10) sCurDate += '0';
         sCurDate += nDateVal.toString() + '/';
         nDateVal = oCurDate.getDate();
         if (nDateVal < 10) sCurDate += '0';
         sCurDate += nDateVal.toString();
         
         // Define the regular expression engine used below.
         UltraEdit.ueReOn();
      
         // Run the following code on every file name (= line) in the list file.
         while( !UltraEdit.document[nListFile].isEof()) {
      
            // Get full name of a file without line termination and move cursor
            // to start of the next line.
            UltraEdit.document[nListFile].startSelect();
            UltraEdit.document[nListFile].key("END");
            sFullName = UltraEdit.document[nListFile].selection;
            UltraEdit.document[nListFile].endSelect();
            UltraEdit.document[nListFile].key("HOME");
            UltraEdit.document[nListFile].key("DOWN ARROW");
      
            // Check if file to open is already open and make it
            // active if this is the case. Otherwise open the file.
            nActiveDocIndex = GetFileIndex(sFullName);
            if (nActiveDocIndex < 0) UltraEdit.open(sFullName);
            else {
               UltraEdit.document[nActiveDocIndex].top();
               UltraEdit.document[nActiveDocIndex].setActive();
            }
      
            // Get name of file and file path.
            sFilePath = GetFilePath(sFullName);
            sFileName = GetNameOfFile(sFullName);
            
            UltraEdit.activeDocument.findReplace.mode=0;
            UltraEdit.activeDocument.findReplace.matchCase=false;
            UltraEdit.activeDocument.findReplace.matchWord=false;
            UltraEdit.activeDocument.findReplace.regExp=true;
            UltraEdit.activeDocument.findReplace.searchDown=true;
            UltraEdit.activeDocument.findReplace.searchInColumn=false;
            UltraEdit.activeDocument.findReplace.preserveCase=false;
            UltraEdit.activeDocument.findReplace.replaceAll=true;
            UltraEdit.activeDocument.findReplace.replaceInAllOpen=false;
            UltraEdit.activeDocument.findReplace.replace("%^(//SELECT +^p ++SELECT +^)^(*^)$", "^1/*XXXXX;FilePath="+sFilePath+";FileName="+sFileName+";Date="+sCurDate+";Area=Main;*/^p         ^2");
            if (nActiveDocIndex < 0) UltraEdit.closeFile(UltraEdit.activeDocument.path,1);
            else UltraEdit.save();
         }
         // List file not closed to see on which files the script was executed.
      }
      I can suggest also a second version for this task. The second script is similar to first one. The difference is that instead of opening, running a replace all, saving and closing (if not already open on script start) each file, the command Replace in Files is used on every file. This makes the second script faster and you can see in the output window which files have been modified.

      Code: Select all

      var g_nDebugMessage=1;  // Enable debug messages to output window.
      
      if (GetListOfFiles (0, "\\\\MyFileShare\\MyFiles\\", "*.txt", false)) {
      
         var sFileName = "";
         var sFilePath = "";
         var sFullName = "";
         var nActiveDocIndex = 0;
      
         // Get file index of list file (= active file).
         var nListFile = GetFileIndex();
      
         // Get current date/time and build date string in required format.
         var oCurDate = new Date();
         var nDateVal = oCurDate.getFullYear();
         var sCurDate = nDateVal.toString() + '/';
         nDateVal = oCurDate.getMonth() + 1;
         if (nDateVal < 10) sCurDate += '0';
         sCurDate += nDateVal.toString() + '/';
         nDateVal = oCurDate.getDate();
         if (nDateVal < 10) sCurDate += '0';
         sCurDate += nDateVal.toString();
      
         // Define the regular expression engine used below.
         UltraEdit.ueReOn();
         // Define once the constant replace in files options.
         UltraEdit.frInFiles.filesToSearch=0;
         UltraEdit.frInFiles.logChanges=true;
         UltraEdit.frInFiles.matchCase=false;
         UltraEdit.frInFiles.matchWord=false;
         UltraEdit.frInFiles.preserveCase=false;
         UltraEdit.frInFiles.searchSubs=false;
         UltraEdit.frInFiles.regExp=true;
      
         // Run the following code on every file name (= line) in the list file.
         while( !UltraEdit.document[nListFile].isEof()) {
      
            // Get full name of a file without line termination and move cursor
            // to start of the next line.
            UltraEdit.document[nListFile].startSelect();
            UltraEdit.document[nListFile].key("END");
            sFullName = UltraEdit.document[nListFile].selection;
            UltraEdit.document[nListFile].endSelect();
            UltraEdit.document[nListFile].key("HOME");
            UltraEdit.document[nListFile].key("DOWN ARROW");
      
            // Get name of file and file path.
            sFilePath = GetFilePath(sFullName);
            sFileName = GetNameOfFile(sFullName);
      
            UltraEdit.frInFiles.directoryStart=sFilePath;
            UltraEdit.frInFiles.searchInFilesTypes=sFileName;
            UltraEdit.frInFiles.replace("%^(//SELECT +^p ++SELECT +^)^(*^)$", "^1/*XXXXX;FilePath="+sFilePath+";FileName="+sFileName+";Date="+sCurDate+";Area=Main;*/^p         ^2");
         }
         UltraEdit.closeFile(UltraEdit.document[nListFile].path,2);
      }
      Best regards from an UC/UE/UES for Windows user from Austria