10 Replies Latest reply on Jul 7, 2015 6:41 AM by xbytor2

    File Name editing if condition applies

    Beracah SB Level 1

      Hello,

       

      Is that possible to read the file name and rename if the condition applies.

       

      Example:

      We receive files with the name as shown below, I need the last 4 digit need to be removed and save the file as .psd formate.

      Some time we receive files with last 4 digit and some time it won't.

       

      Source files:

      4100520_A_799_0626.tif

      4100520_B_650_0626.psd

      4100520_B_400.tif

      41009782_B_039_0626.jpg

       

      Final Required file names as:

      4100520_A_799.psd

      4100520_B_650.psd

      4100520_B_400.psd

      41009782_B_039.psd

        • 1. Re: File Name editing if condition applies
          xbytor2 Level 4

          This should work.

           

          var f = File("4100520_A_799_0626.tif");

          if (f.name.match(/_\d\d\d\d\./) {

             name  = f.name.replace(/_\d\d\d\d\./, '.');

          } else {

             name = f.name;

          }

          • 2. Re: File Name editing if condition applies
            michelr31372089 Level 2

            Hi all,

            Nice problem.

            If you must conserve the 13 first characters of your fileNames, you can try this also :

            // MAC Finder ou WINDOWS Explorer

            #target photoshop

            app.bringToFront();

             

             

            main();

             

             

            function main(){

                // Selection of the folder where images have been copied

                var inputFolder = Folder.selectDialog("Select the folder where your images have been copied : ");

                var outputFolder = Folder(inputFolder + "/save");

                if (!outputFolder.exists) outputFolder.create();

                var fileList = inputFolder.getFiles(/\.(jpg|jpeg|tif|tiff|psd|)$/i);

                // No comment

                app.displayDialogs = DialogModes.NO;

                // If there are photos in the folder

                if (fileList.length>0)

                {

                    for (var i=0;i<fileList.length;i++)

                    {

                        var docRef = open(fileList[i]);

                        var docName  = docRef.name;

                        var docName  = docName.substring( 0, docName.indexOf('.') ); //photo26 et photo43

                        var psd_Options  = new PhotoshopSaveOptions(); // [PhotoshopSaveOptions]

                        psd_Options.layers  = true; // preserve layers

                        psd_Options.embedColorProfile = true; // preserves color profile

                        psd_Options.annotations = true; // preserves notes

                        psd_Options.alphaChannels = true; // preserves alpha channels

                        psd_Options.spotColors = true; // preserves inks

                       

                        var shortName=leftTrim(docName);

                        // Save

                        docRef.saveAs( File(outputFolder + '/' + shortName + ".psd" ), psd_Options, true );

                        app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);

                   }

                }

                alert("Your files have been saved in the \"../save\" sub-folder");

            }

             

            function leftTrim(name)

            {

                    return name.substr(0,13)

            }

            • 3. Re: File Name editing if condition applies
              pixxxel schubser MVP & Adobe Community Professional

              Hi xbytor2,

              xbytor2 schrieb:

               

              This should work.

               

              var f = File("4100520_A_799_0626.tif");

              if (f.name.match(/_\d\d\d\d\./) {

                name  = f.name.replace(/_\d\d\d\d\./, '.');

              } else {

                name = f.name;

              }

               

              You are on the right way.

              But there is no need to add a match-function before replace. This will do the same (without match() and if clause)

              var f = File("4100520_A_799_0626.tif");
              name  = f.name.replace(/_\d{4}\./, '.');
              
              // alert(name)
              
              

               

               

              --------------------------------

               

              michelr31372089

               

              function leftTrim(name)
              {
                      return name.substr(0,13);
              }
              

               

              This seems to be not a good idea --> because of:

              4100520_B_400.tif

              41009782_B_039_0626.jpg

              • 4. Re: File Name editing if condition applies
                michelr31372089 Level 2

                You are 100% right. I thought that we need only the 13 first chars. More interesting !

                • 5. Re: File Name editing if condition applies
                  xbytor2 Level 4

                  But there is no need to add a match-function before replace.

                   

                  I know. I was going for clarity rather than brevity which is usually the best choice for someone who is not familiar with regular expressions.

                  • 6. Re: File Name editing if condition applies
                    Beracah SB Level 1

                    Thank you guys.

                     

                    I have tweak as it works only when the file contains 13 char, else the action prompt for manual interaction.

                    • 7. Re: File Name editing if condition applies
                      pixxxel schubser MVP & Adobe Community Professional

                      Hi Shine_RRD,

                      me too. I don't like the substring method in such cases!

                       

                      Untestet: Try to replace this line (in the script of michelr31372089 )

                      var docName  = docName.substring( 0, docName.indexOf('.') ); //photo26 et photo43
                      

                       

                      with this line

                      docName  = docName.replace( /\..{2,4}$/, ''); // you don't need 'var' it again
                      

                       

                       

                      and furthermore this line

                      return name.substr(0,13)
                      

                       

                      with this

                      return name.replace(/_\d{4}$/, '');
                      

                       

                       

                      This should do the job with all of your different file names.

                      Have fun

                       

                      • 10. Re: File Name editing if condition applies
                        xbytor2 Level 4

                        Here's a function that does File/Folder name formatting in hardcore mode (from xtools/xlib/stdlib.js). I use this a lot. I have several sprintf related functions in stdlib.js that have made scripting a much easier task over the years. Regardless, it's an interesting bit of code to study even if you don't

                         

                        //========================= Filename formatting ===============================
                        //
                        // File.strf(fmt [, fs])
                        // Folder.strf(fmt [, fs])
                        //   This is based on the file name formatting facility in exiftool. Part of
                        //   the description is copied directly from there. You can find exiftool at:
                        //      http://www.sno.phy.queensu.ca/~phil/exiftool/
                        //
                        // Description:
                        //   Format a file string using a printf-like format string
                        //
                        // fmt is a string where the following substitutions occur
                        //   %d - the directory name (no trailing /)
                        //   %f - the file name without the extension
                        //   %e - the file extension without the leading '.'
                        //   %p - the name of the parent folder
                        //   %% - the '%' character
                        //
                        // if fs is true the folder is in local file system format
                        //   (e.g. C:\images instead of /c/images)
                        //
                        // Examples:
                        //
                        // Reformat the file name:
                        // var f = new File("/c/work/test.jpg");
                        // f.strf("%d/%f_%e.txt") == "/c/work/test_jpg.txt"
                        //
                        // Change the file extension
                        // f.strf("%d/%f.psd") == "/c/work/test.psd"
                        //
                        // Convert to a file name in a subdirectory named after the extension
                        // f.strf("%d/%e/%f.%e") == "/c/work/jpg/test.jpg"
                        //
                        // Change the file extension and convert to a file name in a subdirectory named
                        //   after the new extension
                        // f.strf("%d/psd/%f.psd") == "/c/work/psd/test.psd"
                        //
                        // var f = new File("~/.bashrc");
                        // f.strf("%f") == ".bashrc"
                        // f.strf("%e") == ""
                        //
                        // Advanced Substitution
                        //   A substring of the original file name, directory or extension may be
                        //   taken by specifying a string length immediately following the % character.
                        //   If the length is negative, the substring is taken from the end. The
                        //   substring position (characters to ignore at the start or end of the
                        //   string) may be given by a second optional value after a decimal point.
                        // For example:
                        //
                        // var f = new File("Picture-123.jpg");
                        //
                        // f.strf("%7f.psd") == "Picture.psd"
                        // f.strf("%-.4f.psd") == "Picture.psd"
                        // f.strf("%7f.%-3f") == "Picture.123"
                        // f.strf("Meta%-3.1f.xmp") == "Meta12.xmp"
                        //
                        File.prototype.strf = function(fmt, fs) {
                          var self = this;
                          var name = decodeURI(self.name);
                          //var name = (self.name);
                          // get the portions of the full path name
                          // extension
                          var m = name.match(/.+\.([^\.\/]+)$/);
                          var e = m ? m[1] : '';
                          // basename
                          m = name.match(/(.+)\.[^\.\/]+$/);
                          var f = m ? m[1] : name;
                          fs |= !($.os.match(/windows/i)); // fs only matters on Windows
                          // fs |= isMac();
                          // full path...
                          var d = decodeURI((fs ? self.parent.fsName : self.parent.absoluteURI));
                          // parent directory...
                          var p = decodeURI(self.parent.name);
                          //var d = ((fs ? self.parent.fsName : self.parent.toString()));
                          var str = fmt;
                          // a regexp for the format specifiers
                          var rex = /([^%]*)%(-)?(\d+)?(\.\d+)?(%|d|e|f|p)(.*)/;
                          var result = '';
                          while (m = rex.exec(str)) {
                            var pre = m[1];
                            var sig = m[2];
                            var len = m[3];
                            var ign = m[4];
                            var typ = m[5];
                            var post = m[6];
                            var subst = '';
                            if (typ == '%') {
                              subst = '%';
                            } else {
                              var s = '';
                              switch (typ) {
                                case 'd': s = d; break;
                                case 'e': s = e; break;
                                case 'f': s = f; break;
                                case 'p': s = p; break;
                                // default: s = "%" + typ; break; // let others pass through
                              }
                              var strlen = s.length;
                              if (strlen && (len || ign)) {
                                ign = (ign ? Number(ign.slice(1)) : 0);
                                if (len) {
                                  len = Number(len);
                                  if (sig) {
                                    var _idx = strlen - len - ign;
                                    subst = s.slice(_idx, _idx+len);
                                  } else {
                                    subst = s.slice(ign, ign+len);
                                  }
                                } else {
                                  if (sig) {
                                    subst = s.slice(0, strlen-ign);
                                  } else {
                                    subst = s.slice(ign);
                                  }
                                }
                              } else {
                                subst = s;
                              }
                            }
                            result += pre + subst;
                            str = post;
                          }
                          result += str;
                          return result;
                        };
                        Folder.prototype.strf = File.prototype.strf;