Skip to main content
Inspiring
April 28, 2022
Answered

Open file if filename contain specific text

  • April 28, 2022
  • 2 replies
  • 1980 views

How its possible, using javascript, to open file in PS if i know that file name start with some specific text?

For example I have folder /User/Documents/PSD/ with files:

Italy_215.psd

Italy_216.psd

Poland_725.psd

Germany_325.psd

 

My needs are to open all files which contain word Italy in filename, using javascript. Thanks in advance.

This topic has been closed for replies.
Correct answer jazz-y

 

findAndOpen('~/Documents/PSD', 'Italy')

function findAndOpen(folder, text) {
    var fls = Folder(folder).getFiles(),
        r = RegExp('^'+text, 'i');
    for (var i = 0; i < fls.length; i++) {
        var cur = fls[i];
        if (cur instanceof File) {
            if (r.test(decodeURI(cur.name))) open(cur)
        } else findAndOpen(cur, text)
    }
}

 

2 replies

Stephen Marsh
Community Expert
Community Expert
May 1, 2022

As a learning exercise, I wanted to see if I could do this too... These three scripts are slightly different but the same in the end result:

 

var inputFiles = Folder('~/Documents/PSD').getFiles();
for (var a = 0; a < inputFiles.length; a++) {
        if (inputFiles[a].name.indexOf('Italy_') !== -1) {
        open(inputFiles[a]);
    }
}

 

 

 

var inputFiles = Folder('~/Documents/PSD').getFiles();
for (var a = 0; a < inputFiles.length; a++) {
        if (/^Italy_/.test(inputFiles[a].name)) {
        open(inputFiles[a]);
    }
}

 

 

 

var inputFiles = Folder('~/Documents/PSD').getFiles();
for (var a = 0; a < inputFiles.length; a++) {
    if (inputFiles[a].name.match(/^Italy_/)) {
        open(inputFiles[a]);
    }
}

 

I personally prefer the second (faster) and third (slower) option as they offer more flexibility via Regular Expressions (which may not be needed in this particular use case where indexOf suffices).

 

Kukurykus
Legend
May 1, 2022

.IndexOf is fastest, then .split, if used without RegEx in this case.

milevicAuthor
Inspiring
May 4, 2022

Thank you guys

Kukurykus
Legend
April 28, 2022

 

File('~/documents/psd')
.getFiles(function(v){v.name
.indexOf('Italy') + 1 && open(v)})

 

milevicAuthor
Inspiring
April 29, 2022

Great, as always. Thanks @Kukurykus 

Just one more thing, is it possible to get full pathname of single psd in case that numbers at the end are variable. To be more precise, I know that in folder /User/Documents/PSD/ exist psd file which start with word Poland_ and three digits at the end, but i dont know which digits will be. Is it possible somehow to get pathname of that file?

Kukurykus
Legend
April 29, 2022

 

File('~/documents/psd').getFiles(function(v){v.name
.split(/^Poland_\d{3}/).length - 1 && alert(v.fsName)})