Script to rename files and folders

Script to rename files and folders

1002
Power UserPower User
1002

    Jul 28, 2022#1

    Hi.

    I'm handling with more than 2,500 files, all of them named index.html and each of them inside a folder named as date time format, like this:
    20220728004408753

    And facing a problem that is hard to find a solution.
    The only way I believe is using scripts.

    Is there a way to write a script that could grab the name of the page, that is inside <title> tag and rename the file and the folder with that title?
    I'm thinking of "Replace in Files" resource.

    Header of each file is like this:

    Code: Select all

    <!DOCTYPE html><html dir="ltr" data-scrapbook-source="https://clubeceticismo.com.br/viewtopic.php?f=8&amp;t=383" data-scrapbook-create="20220728004408753" lang="pt-br"><head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="favicon.png">
    
    <title>Por onde andam antigos participantes? - Clube Ceticismo</title>
    
        <link rel="alternate" type="application/atom+xml" title="Feed - Clube Ceticismo" href="https://clubeceticismo.com.br/app.php/feed">            <link rel="alternate" type="application/atom+xml" title="Feed - Novos tópicos" href="https://clubeceticismo.com.br/app.php/feed/topics">        <link rel="alternate" type="application/atom+xml" title="Feed - Fórum - Quadro de avisos" href="https://clubeceticismo.com.br/app.php/feed/forum/8">    <link rel="alternate" type="application/atom+xml" title="Feed - Tópico - Por onde andam antigos participantes?" href="https://clubeceticismo.com.br/app.php/feed/topic/383">    
        <link rel="canonical" href="https://clubeceticismo.com.br/viewtopic.php?t=383">
    
    ...
    
    ...
    
    etc...
    
    Script would do the following:
    1 - open the index.html file
    2 - read the title
    3 - close the file
    4 - rename file
    5 - rename folder
    6 - go ahead to the next index.html file

    Thanks.

    6,688587
    Grand MasterGrand Master
    6,688587

      Jul 28, 2022#2

      There is no UltraEdit scripting command to rename an opened file. UltraEdit has a command to rename an opened file, but this command is not available as scripting command.

      The task can be done with a batch file (worst choice), a VBScript script (better) or a PowerShell script (best choice).

      It is possible to create an UltraEdit script which runs a Find in Files for the title element and reformats the found lines to get directory name and title string with all characters not allowed in file names like ? removed finally written into a CSV which can be used next with a for /F command line in a command prompt window to make the file and folder renames.

      Script to create the CSV file for all index.html in C:\Temp\Test and all its non-hidden subdirectories:

      Code: Select all

      // Get all lines containing <title> in all index.html files in directory
      // C:\Temp\Test and all its non-hidden subdirectories written into a
      // new edit window.
      UltraEdit.frInFiles.filesToSearch=0;
      UltraEdit.frInFiles.searchInFilesTypes="index.html";
      UltraEdit.frInFiles.directoryStart="C:\\Temp\\Test\\";
      UltraEdit.frInFiles.ignoreHiddenSubs=true;
      UltraEdit.frInFiles.searchSubs=true;
      UltraEdit.frInFiles.useEncoding=true;
      UltraEdit.frInFiles.encoding=65001;
      UltraEdit.frInFiles.regExp=false;
      UltraEdit.frInFiles.matchCase=false;
      UltraEdit.frInFiles.useOutputWindow=false;
      UltraEdit.frInFiles.find("<title>");
      
      // Convert the Unicode file to ANSI and next to OEM as required by cmd.exe.
      UltraEdit.activeDocument.unicodeToASCII();
      UltraEdit.activeDocument.ansiToOem();
      UltraEdit.activeDocument.top();
      
      // Remove all lines not of interest written into the results file by UE/UES.
      UltraEdit.perlReOn();
      UltraEdit.activeDocument.findReplace.mode=0;
      UltraEdit.activeDocument.findReplace.matchCase=true;
      UltraEdit.activeDocument.findReplace.matchWord=false;
      UltraEdit.activeDocument.findReplace.regExp=true;
      UltraEdit.activeDocument.findReplace.searchDown=true;
      if (typeof(UltraEdit.activeDocument.findReplace.searchInColumn) == "boolean")
      {
         UltraEdit.activeDocument.findReplace.searchInColumn=false;
      }
      UltraEdit.activeDocument.findReplace.preserveCase=false;
      UltraEdit.activeDocument.findReplace.replaceAll=true;
      UltraEdit.activeDocument.findReplace.replaceInAllOpen=false;
      UltraEdit.activeDocument.findReplace.replace("^(?:(?![A-Z]:).*\\r\\n)+","");
      UltraEdit.activeDocument.top();
      
      // Remove some characters definitely not allowed in file names.
      UltraEdit.activeDocument.findReplace.replace("[\t\"*?|]+","");
      UltraEdit.activeDocument.top();
      
      // Convert the remaining lines into a CSV file format using a vertical bar
      // as separator and not a comma because of no file/folder name can contain
      // a vertical bar.
      UltraEdit.activeDocument.findReplace.matchCase=false;
      UltraEdit.activeDocument.findReplace.replace("^(.+?)\\\\index\.html.*?:.*?<title>(.+)</title>.*$",'"\\1"|"\\2"');
      
      // Remove some more characters definitely not allowed in file names.
      UltraEdit.activeDocument.findReplace.matchCase=true;
      UltraEdit.activeDocument.findReplace.replace("[/<>]+","");
      UltraEdit.activeDocument.top();
      
      // Remove all colons and backslashes in new file/folder name.
      while (UltraEdit.activeDocument.findReplace.replace('^.+\\|"[^\\r\\n:\\\\]*+\\K[:\\\\]',"")) UltraEdit.activeDocument.top();
      
      // Save the file as CSV file to process from the command line.
      UltraEdit.saveAs("C:\\Temp\\Test\\RenameFilesFolders.csv");
      
      The directory path C:\Temp\Test in the comment at top of the script as well as in the JavaScript strings "C:\\Temp\\Test\\" at top and "C:\\Temp\\Test\\RenameFilesFolders.csv" at bottom of the script must be adapted to your needs. Please note the escaped backslashes in the JavaScript strings.

      The created CSV file RenameFilesFolders.csv has lines like:

      Code: Select all

      "C:\Temp\Test\20220728004408753"|"Por onde andam antigos participantes - Clube Ceticismo"
      Note: The UltraEdit script as written does not support multi-line title elements. So better make a quick look on the CSV file if all lines look correct.

      Then open a Windows command prompt window, use the command CD to change the current directory to the directory containing the subdirectories and index.html files to rename and the CSV file RenameFilesFolders.csv and run the following command line:

      Code: Select all

      for /F "tokens=1,2 delims=|" %I in (RenameFilesFolders.csv) do @ren "%~I\index.html" "%~J.html"&& ren %I %J
      The result is a rename of 20220728004408753\index.html to Por onde andam antigos participantes - Clube Ceticismo\Por onde andam antigos participantes - Clube Ceticismo.html.
      Best regards from an UC/UE/UES for Windows user from Austria

      1002
      Power UserPower User
      1002

        Jul 28, 2022#3

        Mofi, thank you very much for your attention and prompt response.
        Your solution works very well and I'm grateful to see so fast result.

        Unfortunately, yesterday, late hour, I tried to edit my first post to change some wrong requests, but I'd see no proper button/link to do so.
        Because it was late, I decided to explain it more today. But you were faster and already brought a solution.

        I forgot to explain that the index.html files have to be moved to the parent folder and edited to find its resources (style sheets, pictures, etc.) inside the folders, accordingly.

        To do that, you already wrote a script in the past.
        But it get the folders already named correctly.
        Now, the folders must to be renamed before apply the script.

        Here you are:

        Code: Select all

        //var sParentFolderPath = "";   // A parent folder path can be defined here.
                                        // Note: Each backslash must be escaped with an additional backslash.
        var sParentFolderPath = "F:\\Meus documentos\\Downloads\\1";
        
        // Is no parent folder path defined above?
        if (!sParentFolderPath.length)
        {
           // If there is any file opened, get path of active file.
           if (UltraEdit.document.length > 0)  // Is any file opened?
           {
              sParentFolderPath = GetFilePath();
           }
           // Let script user enter the folder path if no file is opened
           // in UltraEdit or the active file is a new, unsaved file.
           while (!sParentFolderPath.length)
           {
              sParentFolderPath = UltraEdit.getString("Enter path of parent folder:",1);
           }
        }
        
        // Append a backslash if parent folder path does not end already with a backslash.
        if (sParentFolderPath[sParentFolderPath.length-1] != '\\')
        {
           sParentFolderPath += '\\';
        }
        
        // Get all index.html files with full path in specified directory tree.
        if (GetListOfFiles(0,sParentFolderPath,"index.html",true))
        {
           UltraEdit.activeDocument.top();
           UltraEdit.activeDocument.findReplace.mode=0;
           UltraEdit.activeDocument.findReplace.matchCase=false;
           UltraEdit.activeDocument.findReplace.matchWord=false;
           UltraEdit.activeDocument.findReplace.regExp=false;
           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(sParentFolderPath+"index.html\r\n","");
        
           UltraEdit.activeDocument.selectAll();
           if (UltraEdit.activeDocument.isSel())
           {
              var asFileNames = UltraEdit.activeDocument.selection.split("\r\n");
              asFileNames.pop();   // Remove the empty string from end of array.
        
        
              // Convert the find in files results file into a batch file for
              // moving the modified index.html files up to parent folder.
              // The new file name is inserted later on each line.
              UltraEdit.activeDocument.top();
              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("^(.+)$",'move /Y "\\1" "');
              UltraEdit.activeDocument.top();
        
              // Add a line to run later the batch file with less output to console.
              UltraEdit.activeDocument.write("@echo off\r\n");
        
              // Define the parameters for the replace in files executed later.
              UltraEdit.perlReOn();
              UltraEdit.frInFiles.regExp=true;
              UltraEdit.frInFiles.filesToSearch=0;
              UltraEdit.frInFiles.logChanges=true;
              UltraEdit.frInFiles.matchWord=false;
              UltraEdit.frInFiles.matchCase=false;
              UltraEdit.frInFiles.searchSubs=false;
              UltraEdit.frInFiles.directoryStart="";
              UltraEdit.frInFiles.useEncoding=false;
              UltraEdit.frInFiles.preserveCase=false;
              UltraEdit.frInFiles.openMatchingFiles=false;
        
              // Process each file name in the array.
              for (var nFile = 0; nFile < asFileNames.length; nFile++)
              {
                 // Get path of file without parent folder path and without \index.html at end.
                 var sFilePath = asFileNames[nFile].substring(sParentFolderPath.length,asFileNames[nFile].length-11);
                 // URL encode the file path with additionally encode also single straight quotes.
                 var sEncodedFilePath = encodeURI(sFilePath).replace(/\'/g,"%27");
                 sEncodedFilePath = sEncodedFilePath.replace(/&/g,"&amp;");
        
                 // Run the Perl regular expression replace on this index.html file
                 // which inserts the file path on href="..." or href='...' or src="..."
                 // or src='...' or url("...") or url('...') or url(&quot;...&quot;)
                 // file references if those file references do not start with "#",
                 // or "javascript:" or contain already a reference with / in string.
                 UltraEdit.frInFiles.searchInFilesTypes=asFileNames[nFile];
                 UltraEdit.frInFiles.replace("(href=[\"']|src=[\"']|url\\([\"']|url\\(&quot;)(?!#|javascript:)((?:(?![\"']|&quot;)[^/])+(?=[\"']|&quot;))","\\1"+sEncodedFilePath+"/\\2");
        
                 // Remove the string "_files" at end of file path for new file name
                 // if this string is at end of file path at all. Then insert new file
                 // name with path into already reformatted  find in files results file.
              var sNewFileName = sFilePath.replace(/_arquivos$/,"") + ".html";
                 UltraEdit.activeDocument.key("END");
                 UltraEdit.activeDocument.write(sParentFolderPath+sNewFileName+'"');
                 UltraEdit.activeDocument.key("DOWN ARROW");
              }
        
              // Append a line so that the batch file deletes itself on execution.
        //      UltraEdit.activeDocument.write('del "%~f0" & exit\r\n');
        
              // Convert the file from ANSI to OEM to work also for folder paths
              // not consisting of only ASCII characters.
              UltraEdit.activeDocument.ansiToOem();
        
              // Save the reformatted find in files results file as batch file in parent folder.
              UltraEdit.saveAs(sParentFolderPath+"MoveHtmlFiles.bat");
        
              // Run the batch file via a user tool.
              UltraEdit.runTool("Run Active File");
        
              // Close the batch file which has deleted already itself.
              UltraEdit.closeFile(UltraEdit.activeDocument.path,2);
           }
           else
           {
              // Close the empty results file because of nothing to do.
              UltraEdit.closeFile(UltraEdit.activeDocument.path,2);
              UltraEdit.messageBox("No index.html file found in a subdirectory of "+sParentFolderPath);
           }
        }
        
        function GetFilePath (CompleteFileNameOrDocIndexNumber)
        {
           var sFilePath = "";
           var sFullFileName = "";
           var nLastDirDelim = -1;
           var nOutputType = (typeof(g_nDebugMessage) == "number") ? g_nDebugMessage : 0;
           if (typeof(CompleteFileNameOrDocIndexNumber) == "string")
           {
              sFullFileName = CompleteFileNameOrDocIndexNumber;
              nLastDirDelim = sFullFileName.lastIndexOf("|");
              if (nLastDirDelim < 0)
              {
                 var nLastSlash = sFullFileName.lastIndexOf("/");
                 var nLastBackSlash = sFullFileName.lastIndexOf("\\");
                 nLastDirDelim = (nLastBackSlash > nLastSlash) ? nLastBackSlash : nLastSlash;
              }
              if (nLastDirDelim < 0)
              {
                 if (nOutputType == 2)
                 {
                    UltraEdit.messageBox("File path can't be determined from \""+sFullFileName+"\"!","GetFilePath Error");
                 }
                 else if (nOutputType == 1)
                 {
                    if (!UltraEdit.outputWindow.visible) UltraEdit.outputWindow.showWindow(true);
                    UltraEdit.outputWindow.write("GetFilePath: File path can't be determined from \""+sFullFileName+"\"!");
                 }
                 return sFilePath;
              }
           }
           else
           {
              if (UltraEdit.document.length < 1)
              {
                 if (nOutputType == 2)
                 {
                    UltraEdit.messageBox("No document is open currently!","GetFilePath Error");
                 }
                 else if (nOutputType == 1)
                 {
                    if (!UltraEdit.outputWindow.visible) UltraEdit.outputWindow.showWindow(true);
                    UltraEdit.outputWindow.write("GetFilePath: No document is open currently!");
                 }
                 return sFilePath;
              }
              var nDocumentNumber = -1;
              if (typeof(CompleteFileNameOrDocIndexNumber) == "number")
              {
                 nDocumentNumber = CompleteFileNameOrDocIndexNumber;
              }
              if (nDocumentNumber >= UltraEdit.document.length)
              {
                 if (nOutputType == 2)
                 {
                    UltraEdit.messageBox("A document with index number "+nDocumentNumber+" does not exist!","GetFilePath Error");
                 }
                 else if (nOutputType == 1)
                 {
                    if (!UltraEdit.outputWindow.visible) UltraEdit.outputWindow.showWindow(true);
                    UltraEdit.outputWindow.write("GetFilePath: A document with index number "+nDocumentNumber+" does not exist!");
                 }
                 return sFilePath;
              }
              if (nDocumentNumber < 0)
              {
                 sFullFileName = UltraEdit.activeDocument.path;
                 if (UltraEdit.activeDocument.isFTP())
                 {
                    nLastDirDelim = sFullFileName.lastIndexOf("|");
                    if (nLastDirDelim < 0) nLastDirDelim = sFullFileName.lastIndexOf("/");
                 }
              }
              else
              {
                 sFullFileName = UltraEdit.document[nDocumentNumber].path;
                 if (UltraEdit.document[nDocumentNumber].isFTP())
                 {
                    nLastDirDelim = sFullFileName.lastIndexOf("|");
                    if (nLastDirDelim < 0) nLastDirDelim = sFullFileName.lastIndexOf("/");
                 }
              }
              if (nLastDirDelim < 0) nLastDirDelim = sFullFileName.lastIndexOf("\\");
              if (nLastDirDelim < 0)
              {
                 if (nOutputType == 2)
                 {
                    UltraEdit.messageBox("File path can't be determined from a new file!","GetFilePath Error");
                 }
                 else if (nOutputType == 1)
                 {
                    if (!UltraEdit.outputWindow.visible) UltraEdit.outputWindow.showWindow(true);
                    UltraEdit.outputWindow.write("GetFilePath: File path can't be determined from a new file!");
                 }
                 return sFilePath;
              }
           }
           if (sFullFileName.charAt(nLastDirDelim) != '|')
           {
              nLastDirDelim++;
              sFilePath = sFullFileName.substring(0,nLastDirDelim);
           }
           else
           {
              sFilePath = sFullFileName.substring(0,nLastDirDelim) + "/";
           }
           return sFilePath;
        }
        
        function GetListOfFiles (nFileList, sDirectory, sFileType, bSubDirs)
        {
           var sSummaryInfo = "Search complete. Found";
           var sResultsDocTitle = "** Find Results ** ";
           var bNoUnicode = true;
           var nOutputType = (typeof(g_nDebugMessage) == "number") ? g_nDebugMessage : 2;
           if ((nOutputType < 1) || (nOutputType > 2)) nOutputType = 0;
           if (typeof(nFileList) != "number" || nFileList < 0 || nFileList > 4) nFileList = 0;
           if (!nFileList)
           {
              if ((typeof(sDirectory) != "string") || (!sDirectory.length)) sDirectory = ".\\";
              else if (sDirectory[sDirectory.length-1] != "\\") sDirectory += "\\";
              if ((typeof(sFileType) != "string") || (!sFileType.length)) sFileType = "*";
              if (typeof(bSubDirs) != "boolean") bSubDirs = false;
           }
           else
           {
              sDirectory = "";
              sFileType = "";
              bSubDirs = false;
           }
           var nRegexEngine = UltraEdit.regexMode;
           UltraEdit.ueReOn();
           UltraEdit.frInFiles.directoryStart=sDirectory;
           UltraEdit.frInFiles.filesToSearch=nFileList;
           UltraEdit.frInFiles.matchCase=false;
           UltraEdit.frInFiles.matchWord=false;
           UltraEdit.frInFiles.regExp=false;
           UltraEdit.frInFiles.searchInFilesTypes=sFileType;
           UltraEdit.frInFiles.searchSubs=bSubDirs;
           UltraEdit.frInFiles.unicodeSearch=false;
           UltraEdit.frInFiles.useOutputWindow=false;
           if (typeof(UltraEdit.frInFiles.openMatchingFiles) == "boolean")
           {
              UltraEdit.frInFiles.openMatchingFiles=false;
           }
           UltraEdit.frInFiles.find("");
           var bListCreated = false;
           if (UltraEdit.activeDocument.path == sResultsDocTitle) bListCreated = true;
           else
           {
              for (var nDocIndex = 0; nDocIndex < UltraEdit.document.length; nDocIndex++)
              {
                 if (UltraEdit.document[nDocIndex].path == sResultsDocTitle)
                 {
                    UltraEdit.document[nDocIndex].setActive();
                    bListCreated = true;
                    break;
                 }
              }
           }
           if (bListCreated && sSummaryInfo.length)
           {
              UltraEdit.activeDocument.findReplace.searchDown=false;
              UltraEdit.activeDocument.findReplace.matchCase=true;
              UltraEdit.activeDocument.findReplace.matchWord=false;
              UltraEdit.activeDocument.findReplace.regExp=false;
              UltraEdit.activeDocument.findReplace.find(sSummaryInfo);
              bListCreated = UltraEdit.activeDocument.isFound();
           }
           UltraEdit.activeDocument.findReplace.searchDown=true;
           switch (nRegexEngine)
           {
              case 1:  UltraEdit.unixReOn(); break;
              case 2:  UltraEdit.perlReOn(); break;
              default: UltraEdit.ueReOn();   break;
           }
           if (!bListCreated)
           {
              if (nOutputType == 2)
              {
                 UltraEdit.messageBox('There is a problem with command frInFiles or the strings of the two script variables "sSummaryInfo" and "sResultsDocTitle" are not adapted to used version of UltraEdit/UEStudio!',"GetListOfFiles Error");
              }
              else if (nOutputType == 1)
              {
                 if (!UltraEdit.outputWindow.visible) UltraEdit.outputWindow.showWindow(true);
                 UltraEdit.outputWindow.write('GetListOfFiles: There is a problem with command frInFiles or the strings of the two script variables');
                 UltraEdit.outputWindow.write('                "sSummaryInfo" and "sResultsDocTitle" are not adapted to used version of UltraEdit/UEStudio!');
              }
              return false;
           }
           if (sSummaryInfo.length) UltraEdit.activeDocument.deleteLine();
           UltraEdit.activeDocument.top();
           if (bNoUnicode)
           {
              UltraEdit.activeDocument.key("RIGHT ARROW");
              if (UltraEdit.activeDocument.currentPos > 1) UltraEdit.activeDocument.unicodeToASCII();
              else UltraEdit.activeDocument.top();
           }
           if (UltraEdit.activeDocument.isEof())
           {
              if (nOutputType > 0)
              {
                 var sMessage;
                 switch (nFileList)
                 {
                    case 0:  sMessage = "No file " + sFileType + " was found in directory" +
                                        ((nOutputType == 2) ? "\n\n" : " ") + sDirectory; break;
                    case 1:  sMessage = "There are no opened files."; break;
                    case 2:  sMessage = "There are no favorite files."; break;
                    case 3:  sMessage = "There are no project files or no project is opened."; break;
                    case 4:  sMessage = "There are no solution files or no solution is opened."; break;
                    default: sMessage = ""; break;
                 }
                 if (nOutputType == 1)
                 {
                    if (!UltraEdit.outputWindow.visible) UltraEdit.outputWindow.showWindow(true);
                    UltraEdit.outputWindow.write("GetListOfFiles: "+sMessage);
                 }
                 else UltraEdit.messageBox(sMessage,"GetListOfFiles Error");
              }
              UltraEdit.closeFile(UltraEdit.activeDocument.path,2);
              return false;
           }
           return true;
        }
        
        Now, how to integrate the above script with the new one that you wrote today?

        The tree I'm looking for is like this:

        Code: Select all

        C:\Tests\
        |   Renamed 1.html
        |   Renamed 2.html
        |   Renamed 3.html
        |   
        +---Renamed 1
        |       09e21e0c407686fada8f091959db2a2afe67b008.png
        |       147.jpg
        |       304.png
        |       49.gif
        |       924d9a6e764d2010a92fc86415a214ce6317ca41.gif
        |       b0ac20351839be9c93a1d1d58bdd23fc5a2c205a.svg
        |       c0bf984b0de3861cebf7b94997a41b82d6421727.svg
        |       
        +---Renamed 2
        |       FIc37VKXEAYs_fv.jpeg
        |       FIc51dRWQAMXnC1.jpeg
        |       font-awesome.min.css
        |       fontawesome-webfont-1.eot
        |       fontawesome-webfont.eot
        |       fontawesome-webfont.svg
        |       
        \---Renamed 3
                fontawesome-webfont.ttf
                fontawesome-webfont.woff
                fontawesome-webfont.woff2
                hqdefault-1.jpg
                hqdefault-2.jpg
                hqdefault-3.jpg

        6,688587
        Grand MasterGrand Master
        6,688587

          Jul 28, 2022#4

          I am now completely confused about the task. Please compress into a 7-Zip, RAR or ZIP archive file one HTML file with its subdirectory containing the other files without these other files in the subdirectory, i.e. the file Renamed 1.html and the directory Renamed 1 or whatever are the file and folder names before running the script and the batch file. Then rename the file / folder manually and change also the contents of the HTML file manually to what you want and verify if all is correct including the correct percent encoding of all urls. Then compress the modified HTML file and the renamed folder without the files in this folder into one more archive file. Finally write a new post and attach both archive files so that I can see what to modify and have also an example for testing the UltraEdit script and the created batch file.
          Best regards from an UC/UE/UES for Windows user from Austria

          1002
          Power UserPower User
          1002

            Jul 28, 2022#5

            Thank you, Mofi, for your time and attention to the problem.

            I apologize about the edit button. It was my fault. I use an extension to prevent some JavaScript scripts to run on some web pages (NoScript). I forgot to allow UltraEdit forum scripts to run and, thus, I could not see the link to make editions. Sorry.

            I also apologize for my poor explanation of the situation and it has lead to your confusion.

            There are three 7-Zip files attached to this post.
            As requested, I put a tree where folders are already manually renamed in the first 7z file.
            I included all files to let you see that the pages are 100% functionally.

            The second 7z file contains a tree after that other script you wrote.
            It adjusts href, src and url tags to use the name of folders, because index.html will be moved to the folder parent.
            And I put the batch file that perform that move.
            That batch file is created by the script.

            As you can see, the moved HTML files can open the pages correctly.
            Success!

            Now, the task is something different.
            I have thousand of folders and could not rename them manually.
            As I ask for, I need a script to capture the title of each page, rename index.html, rename its folder and move it to its parent.

            In other words, the tree needs to be the same as the second 7z file, given the third 7z file, i.e. with the tree inside third 7z file, I need a tree equal to the second 7z file.

            I tried to be clear. Sorry if I couldn't.

            I guess that we are very close to the final solution.
            Because your two scripts already do all the main challenges.
            Now, it's just to integrate one with another.
            1before.7z (695.06 KiB)   4
            2after.7z (695.76 KiB)   4
            3 - current task.7z (694.87 KiB)   5

            6,688587
            Grand MasterGrand Master
            6,688587

              Jul 29, 2022#6

              Okay, now I understood the task. Here is the entire code for the UltraEdit/UEStudio script which makes the url updates in all the index.html files and creates the batch file to move the files up into parent folder with new name and change the folder names, too. The last two lines are commented and can be uncommented by you on still having the user tool with name Run Active File to run the batch file as last step.

              Code: Select all

              // Get all lines containing <title> in all index.html files in directory
              // F:\Meus documentos\Downloads\1 and all its non-hidden subdirectories
              // written into a new edit window.
              var sParentFolderPath = "F:\\Meus documentos\\Downloads\\1\\";
              
              // Is no parent folder path defined above?
              if (!sParentFolderPath.length)
              {
                 // If there is any file opened, get path of active file.
                 if (UltraEdit.document.length > 0)  // Is any file opened?
                 {
                    sParentFolderPath = GetFilePath();
                 }
                 // Let script user enter the folder path if no file is opened
                 // in UltraEdit or the active file is a new, unsaved file.
                 while (!sParentFolderPath.length)
                 {
                    sParentFolderPath = UltraEdit.getString("Enter path of parent folder:",1);
                 }
              }
              
              // Append a backslash if parent folder path does not end already with a backslash.
              if (sParentFolderPath[sParentFolderPath.length-1] != '\\')
              {
                 sParentFolderPath += '\\';
              }
              
              // Define the parameters for the find in files executed below.
              UltraEdit.frInFiles.filesToSearch=0;
              UltraEdit.frInFiles.searchInFilesTypes="index.html";
              UltraEdit.frInFiles.directoryStart=sParentFolderPath;
              UltraEdit.frInFiles.ignoreHiddenSubs=true;
              UltraEdit.frInFiles.searchSubs=true;
              UltraEdit.frInFiles.useEncoding=true;
              UltraEdit.frInFiles.encoding=65001;
              UltraEdit.frInFiles.regExp=false;
              UltraEdit.frInFiles.matchCase=false;
              UltraEdit.frInFiles.matchWord=false;
              UltraEdit.frInFiles.useOutputWindow=false;
              UltraEdit.frInFiles.openMatchingFiles=false;
              UltraEdit.frInFiles.find("<title>");
              
              // Convert the Unicode file to ANSI and next to OEM as required by cmd.exe.
              UltraEdit.activeDocument.unicodeToASCII();
              UltraEdit.activeDocument.ansiToOem();
              UltraEdit.activeDocument.top();
              
              // Remove all lines not of interest written into the results file by UE/UES.
              UltraEdit.perlReOn();
              UltraEdit.activeDocument.findReplace.mode=0;
              UltraEdit.activeDocument.findReplace.matchCase=true;
              UltraEdit.activeDocument.findReplace.matchWord=false;
              UltraEdit.activeDocument.findReplace.regExp=true;
              UltraEdit.activeDocument.findReplace.searchDown=true;
              if (typeof(UltraEdit.activeDocument.findReplace.searchInColumn) == "boolean")
              {
                 UltraEdit.activeDocument.findReplace.searchInColumn=false;
              }
              UltraEdit.activeDocument.findReplace.preserveCase=false;
              UltraEdit.activeDocument.findReplace.replaceAll=true;
              UltraEdit.activeDocument.findReplace.replaceInAllOpen=false;
              UltraEdit.activeDocument.findReplace.replace("^(?:(?![A-Z]:).*\\r\\n)+","");
              UltraEdit.activeDocument.top();
              
              // Remove some characters definitely not allowed in file names.
              UltraEdit.activeDocument.findReplace.replace("[\t\"*?|]+","");
              UltraEdit.activeDocument.top();
              
              // Convert the remaining lines into a CSV file format using a vertical bar
              // as separator and not a comma because of no file/folder name can contain
              // a vertical bar.
              UltraEdit.activeDocument.findReplace.matchCase=false;
              UltraEdit.activeDocument.findReplace.replace("^(.+?)\\\\index\.html.*?:.*?<title>(.+)</title>.*$",'\\1|\\2');
              
              // Remove some more characters definitely not allowed in file names.
              UltraEdit.activeDocument.findReplace.matchCase=true;
              UltraEdit.activeDocument.findReplace.replace("[/<>]+","");
              UltraEdit.activeDocument.top();
              
              // Remove all colons and backslashes in new file/folder names.
              while (UltraEdit.activeDocument.findReplace.replace('^.+\\|[^\\r\\n:\\\\]*+\\K[:\\\\]',"")) UltraEdit.activeDocument.top();
              
              // Get the file contents as string block.
              UltraEdit.activeDocument.selectAll();
              var sFileNames = UltraEdit.activeDocument.selection;
              UltraEdit.activeDocument.top();
              
              // Convert the CSV file into a Windows batch file
              // to move the HTML files and rename the folders.
              UltraEdit.activeDocument.findReplace.replace("(.+)\\|(.+)$",'move /Y "\\1\\\\index.html" "' +
                                                           sParentFolderPath.replace(/\\/g,"\\\\") +
                                                           '\\2.html" >nul && ren "\\1" "\\2"');
              UltraEdit.activeDocument.top();
              UltraEdit.activeDocument.write("@echo off\r\n");
              
              // Save the file as CSV file to process from the command line.
              UltraEdit.saveAs(sParentFolderPath+"MoveHtmlFiles.bat");
              
              // Overwrite the batch file contents with previous CSV file contents,
              // convert the characters back from OEM to ANSI and modify the lines in
              // the CSV file to file name and folder path separated by a vertical bar.
              UltraEdit.activeDocument.selectAll();
              UltraEdit.activeDocument.write(sFileNames);
              UltraEdit.activeDocument.oemToAnsi();
              UltraEdit.activeDocument.top();
              UltraEdit.activeDocument.findReplace.replace("(.+)\\|","\\1\\\\index.html|");
              
              // Get this list of file/folder names as an array of strings.
              sFileName = "";
              UltraEdit.activeDocument.selectAll();
              var asFileNames = UltraEdit.activeDocument.selection.split("\r\n");
              asFileNames.pop();   // Remove the empty string from end of array.
              // Close the file without saving it as not being anymore a batch file.
              UltraEdit.closeFile(UltraEdit.activeDocument.path,2);
              
              
              // Define the parameters for the replace in files executed later.
              UltraEdit.frInFiles.regExp=true;
              UltraEdit.frInFiles.logChanges=true;
              UltraEdit.frInFiles.searchSubs=false;
              UltraEdit.frInFiles.directoryStart="";
              
              // Defined the variables needed in the loop below to modify all references
              // in all the index.html later moved up and renamed by the batch file.
              var nSeparatorPosition;
              var sEncodedFilePath;
              var sFileName;
              var sFolderName;
              
              // Process each file/folder name in the array.
              for (var nFile = 0; nFile < asFileNames.length; nFile++)
              {
                 // Get file name and folder name of the referenced files separated.
                 nSeparatorPosition = asFileNames[nFile].indexOf('|');
                 sFileName = asFileNames[nFile].substr(0,nSeparatorPosition);
                 sFolderName = asFileNames[nFile].substr(nSeparatorPosition+1);
                 // URL percent encode the folder name with additionally encoding
                 // also the single straight quotes and all ampersands.
                 sEncodedFilePath = encodeURI(sFolderName).replace(/\'/g,"%27");
                 sEncodedFilePath = sEncodedFilePath.replace(/&/g,"&amp;");
              
                 // Run the Perl regular expression replace on this index.html file
                 // which inserts the file path on href="..." or href='...' or src="..."
                 // or src='...' or url("...") or url('...') or url(&quot;...&quot;)
                 // file references if those file references do not start with "#",
                 // or "javascript:" or contain already a reference with / in string.
                 UltraEdit.frInFiles.searchInFilesTypes=sFileName;
                 UltraEdit.frInFiles.replace("(href=[\"']|src=[\"']|url\\([\"']|url\\(&quot;)(?!#|javascript:)((?:(?![\"']|&quot;)[^/])+(?=[\"']|&quot;))","\\1"+sEncodedFilePath+"/\\2");
              }
              
              // Open the batch file in parent folder and execute it via a user tool
              //UltraEdit.open(sParentFolderPath+"MoveHtmlFiles.bat");
              //UltraEdit.runTool("Run Active File");
              
              Best regards from an UC/UE/UES for Windows user from Austria

              1002
              Power UserPower User
              1002

                Jul 29, 2022#7

                Excelente, Mr. Mofi, wonderful!

                Aplausos-e-trabalho - Palmas - Parabéns - Grupo-Equipe.jpg (78.38KiB)


                All tasks were reached.
                Success!

                Thank you.


                Thread SOLVED.