Login  Register

Re: exec() bug in handling embedded blanks

Posted by Michael Schmid on Jul 22, 2014; 10:01am
URL: http://imagej.273.s1.nabble.com/exec-bug-in-handling-embedded-blanks-tp5008844p5008847.html

Hi Neil,

you can use quotes in the unix (linux, etc.) command line because the unix shell handles them: An item in quotes is taken as a single argument for the program's arg list (in the current case, the program is "ls").

ImageJ does not remove the quotes, so the 'ls' command will look for something like
  '/home/user1/'*avg.txt
including the quotes, thus directory name ' with respect to the current directory, then subdirectory home, subdirectory user, filename '*avg.txt
Obviously, that's not what you want.

You can pass the call to the shell:
  cmd="sh -c ls '"+directory+"/'*avg.txt";

Then the shell will care about removing the quotes and creating the proper list of arguments for the ls program.

---

The nicer way of doing it would be using getFileList() and filtering the result (this is independent of the operating system):

   list = getFileList(dir);
   for (i=0; i<list.length; i++) {
      if (endsWith(list[i], "avg.txt")) {
          //handle the file
      }
   }


Michael
________________________________________________________________
On Jul 22, 2014, at 04:59, Neil Fazel wrote:

> I'm using exec() to run a native command from the ImageJ macro code. This code (note the single quotes inside the double quotes)
>
>   cmd="ls '"+directory+"/'*avg.txt";
>   print(cmd);
>   templist = exec(cmd);
>
> doesn't seem to work (templist is blank) whereas if I copy the value of cmd from the log window to the Unix prompt, it works. I think it's because the variable 'directory' has embedded blanks in it and exec() can't handle blanks in path names.
>
> I'm working on Mac and it is not uncommon for directory paths to have blanks in them. Is there a way around this?
>
> BTW, the reason I'm using exec() is because getFileList() doesn't work with wildcards, so exec() seems to be the only way I can get a list of the files matching a certain pattern.
>
> Thanks,
> Neil

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html