Filename extract and rename

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
8 messages Options
Reply | Threaded
Open this post in threaded view
|

Filename extract and rename

richieclose
I'm looking to build out a macro which will extract all file names in a directory, and perform a rename on the file before saving the new file name out to a text file.  The first piece I can do using macro's already
available, but I'm struggling trying to figure out the latter.

A typical filename would look something like this: *image_D2016-02-02T10-30-23-653793Z_0.JPG* and what I would like to do is rename it to *T10-30-23-653793Z_0.JPG* (everything from the letter 'T' onwards).

Any help would be much appreciated!

Thanks

Richie
Reply | Threaded
Open this post in threaded view
|

Re: Filename extract and rename

Herbie
Good day Richie,

please have a look at the "Built-in Macro Functions"-manual that is
available via:
<http://rsb.info.nih.gov/ij/developer/index.html>

There are quite a number of text-processing functions that will help you
performing what you need.

E.g.
startsWith, endsWith, indexOf, substring, matches

But be also aware that ImageJ is about image processing not text
processing or general file handling.

HTH

Herbie

:::::::::::::::::::::::::::::::::::::::::
Am 03.02.16 um 10:25 schrieb richieclose:

> I'm looking to build out a macro which will extract all file names in a
> directory, and perform a rename on the file before saving the new file name
> out to a text file.  The first piece I can do using macro's already
> available, but I'm struggling trying to figure out the latter.
>
> A typical filename would look something like this:
> *image_D2016-02-02T10-30-23-653793Z_0.JPG* and what I would like to do is
> rename it to *T10-30-23-653793Z_0.JPG* (everything from the letter 'T'
> onwards).
>
> Any help would be much appreciated!
>
> Thanks
>
> Richie
>
>
>
> --
> View this message in context: http://imagej.1557.x6.nabble.com/Filename-extract-and-rename-tp5015526.html
> Sent from the ImageJ mailing list archive at Nabble.com.
>
> --
> ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html
Reply | Threaded
Open this post in threaded view
|

Re: Filename extract and rename

richieclose
Thanks Herbie - you're probably right in that using imagej for text processing would not be ideal, but I am looking to minimise the number of tools/programming languages I have to learn!

I was looking that the text-processing functions but not sure if they are suitable as the file length will vary and it turns out I'll need to remove the .jpg also.  Would the split functional be more suitable?  Also, are there any good examples of split being implementing in a macro?
Reply | Threaded
Open this post in threaded view
|

Re: Filename extract and rename

Laurent.guerard
Hi,

What you could do is use this in a loop to remove the extension :

ImgName = Files[i];
StrInd1 = indexOf(ImgName, ".JPG");
//Get the name without the extension
ShortFileName=substring(ImgName,0, StrInd1);

Then depending on the way your images are called, you could use
indexOf(ShortFileName,"T10-something") to get the position in the whole
name of the part you're interested in and then use substring to only get
the part you'd like your files to be named with.

Hope this helps.

--
Laurent Guerard

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html
Reply | Threaded
Open this post in threaded view
|

Re: Filename extract and rename

Michael Entrup
In reply to this post by richieclose
Hi Richie,

if you are willing to learn a bit RegExp (regular expressions), the
following macro code can help:

```
var name = getString("Enter file name:",
"image_D2016-02-02T10-30-23-653793Z_0.JPG");
var code = "var pattern =
/\\w+_D\\d{4}-\\d{2}-\\d{2}T([\\d-_\\w]+)\\.JPG/i;\n";
code += "pattern.exec('" + name + "');\n";
code += "RegExp.$1;";
var returned = eval("script", code);
showMessage("Extracted", "The following string was extracted:\n" +
returned);
```

It uses the function ``eval()`` to run JavaScript code. There is a short
reference [1] on RegExp for JavaScript. The main concept is to use
metacharacters (you need to use 2 backslashes as the first one escapes
the second one) and quantifiers. ``\\d{4}`` stands for 4 digits.

The dot '.' is a special metacharacter that matches nearly everything.
That is why I use ``\\.``. This tells RegExp to search for the character
'.'.

``([\\d-_\\w]+)`` uses two types of groups. Everything inside the [] is
a list of possible matches. It matches to a digit, '-', '_' and a word
character. The '+' stands for one or more of these. The () will save the
content to a variable. After running ``exec()``, you can access the
variables by using ``RegExp.$1``, ``RegExp.$2`` and so on. In this case
there is only one pair of () and only ``RegExp.$1`` contains a value.

If you add () around ``\\d{4}`` and both ``\\d{2}`` you can use them to
include the date into your result. ``RegExp.$1`` will be the year,
``RegExp.$2`` the month and ``RegExp.$3`` the day. This results in
``RegExp.$4`` to be the string you search for.

var code = "var pattern =
/\\w+_D(\\d{4})-(\\d{2})-(\\d{2})T([\\d-_\\w]+)\\.JPG/i;\n";

The 'i' at the end of the pattern stands for case-insensitive matching
and allows to find 'JPG', when searching for 'jpg'.

To get the match, you have to collect the return value of ``eval()``.
This function will return the last expression of the evaluated script
(see ``runMacro()`` [2]).

Regular expression are a bit confusing, when using them for the first
time. But there is a lot of software that can use regular expressions
(e.g. lots of text editors, not including notepad . It's worth to spend
some time to learn the basics.

Best regards
Michael


[1]: http://www.w3schools.com/jsref/jsref_obj_regexp.asp
[2]: http://rsbweb.nih.gov/ij/developer/macro/functions.html#runMacro


On 03.02.2016 10:25, richieclose wrote:

> I'm looking to build out a macro which will extract all file names in a
> directory, and perform a rename on the file before saving the new file name
> out to a text file.  The first piece I can do using macro's already
> available, but I'm struggling trying to figure out the latter.
>
> A typical filename would look something like this:
> *image_D2016-02-02T10-30-23-653793Z_0.JPG* and what I would like to do is
> rename it to *T10-30-23-653793Z_0.JPG* (everything from the letter 'T'
> onwards).
>
> Any help would be much appreciated!
>
> Thanks
>
> Richie
>
>
>
> --
> View this message in context: http://imagej.1557.x6.nabble.com/Filename-extract-and-rename-tp5015526.html
> Sent from the ImageJ mailing list archive at Nabble.com.
>
> --
> ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html
Reply | Threaded
Open this post in threaded view
|

Re: Filename extract and rename

Herbie
In reply to this post by richieclose
Richie,

why didn't you follow my suggestions? It's really easy.

Here is a snippet that does the desired text-processing
(please watch for line breaks introduced by the mailer):

f_name = "image_D2016-02-02T10-30-23-653793Z_0.JPG";
f_name = substring( f_name, indexOf( f_name, "T" ), lengthOf( f_name )-4 );
print( f_name );

HTH

Herbie

:::::::::::::::::::::::::::::::::::::::::
Am 04.02.16 um 08:57 schrieb richieclose:

> Thanks Herbie - you're probably right in that using imagej for text
> processing would not be ideal, but I am looking to minimise the
> number of tools/programming languages I have to learn!
>
> I was looking that the text-processing functions but not sure if they
> are suitable as the file length will vary and it turns out I'll need
> to remove the .jpg also.  Would the split functional be more
> suitable?  Also, are there any good examples of split being
> implementing in a macro?
>
>
>
> -- View this message in context:
> http://imagej.1557.x6.nabble.com/Filename-extract-and-rename-tp5015526p5015534.html
>
>
Sent from the ImageJ mailing list archive at Nabble.com.
>
> -- ImageJ mailing list: http://imagej.nih.gov/ij/list.html
>

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html
Reply | Threaded
Open this post in threaded view
|

Re: Filename extract and rename

richieclose
Hi all

Thanks a million for taking the time to post and provide help - looks like I'm going to need time brush up on my coding skills.  But there's plenty here to help my solve my most immediate problem!

Richie

Reply | Threaded
Open this post in threaded view
|

Re: Filename extract and rename

richieclose
Arragh - thought I was there!  I've written the script below.  And seems to work fine where there is one folder, but I'd like to check sub folders also, so,
Selected source folder-->subfolder 1
                              -->subfolder 2
                              -->subfolder 3

It looks like the script works if there is only one folder, but I get an error if there are multiple folders:
Row(2) out of range in line 32
setResult("File name", i, f_name<)>;


It looks like my index is not increasing after one file name has been processed... but not sure.  Any help would be much appreciated.

dirs = getDirectory("Choose a Source Directory ");
dird = getDirectory("Choose a destination Directory");
setBatchMode(true);
run("Clear Results");
   count = 0;

   n = 0;

processFiles(dirs);

function processFiles(dirs) {
      list = getFileList(dirs);
      for (i=0; i<list.length; i++) {
          if (endsWith(list[i], "/"))
              processFiles(""+dirs+list[i]);
          else {
             showProgress(n++, count);
             path = dirs+list[i];
             processFile(path);
        i++;
          }
      }
  }


function processFile(path){

f_name = list[i];
               
                if (endsWith(path, ".jpg"))
                {
                        setResult("File name",i,f_name);
                       
                        string1 = substring(f_name,25,26);
                        string2 = substring(f_name,27,33);
                        f_name = (string1+string2);
                        setResult("Time Stamp",i,f_name);
                        print(f_name);
                       
}
}

setOption("ShowRowNumbers", false);
updateResults;

path = dird + "image_names.csv";
saveAs("Results", path);
 
if (isOpen("Log")) {
         selectWindow("Log");
         run("Close");
     }
  if (isOpen("Results")) {
         selectWindow("Results");
         run("Close");
     }
showMessage("Image processing complete")