2

Working on zsh on MacOS...

I was wondering if there was a way to query files via an index # of the current directory. For example, if ls outputs:

folder1
folder2
file1.txt
file2.txt

I was wondering if there was a way to run a command such as open $FILES[2] to open file1.txt (assuming 0 index).

I noticed that the command open * opened all individual folders and files of the current directory (finder/default apps), but commands like open *[0] weren't recognized.

My end goal is to find an easy way to both open and pass files, whose names are particularly long to other programs. A screenshot for example typically has a long file name and if I wanted to pass to ImageMagik or something, I figured this sort of file reference would be most efficient.

I should mention I'd be willing to switch from zsh to bash if this were an option there.

2
  • Just a comment because I am not sure, but I don't think so since the number is actually part of the file name and not an index as a variable.
    – agarza
    Commented Sep 2, 2022 at 3:23
  • What is the index number of a directory? Commented Oct 5, 2022 at 7:10

1 Answer 1

3

Files have no inherent ordering on the filesystem, though can be sorted by name, modification time, or so forth; with ZSH you can select by say the most (or least) recently modified, if you can remember (or tab complete) on the single character flags involved:

% mkdir test
% cd test
% touch a
% touch b
% touch c
% print *(om[1])
c
% print *(Om[1])
a
% touch aa
% print *(om[1])
aa
% touch aaa
% print *(om[1])
aaa

By name is available but good luck counting to some file in the middle of the list (or maybe you're better at doing that math in your head than I am?):

% print *(on[1])
a
% print *(On[1])
c
% touch zzz
% print *(On[1])
zzz

Other sorting options are available, though besides the first or last it's probably not very viable for selecting a random filename. To select by a number you'd need software that would associate some number with the files loaded into an array, then a means to input some number to pick some filename. Doable, but maybe not the best interface. There are tools like fzf that might be better at file selection.

Usually for long filenames one will enable tab completion in the shell. Both bash and zsh support this, though it may require configuration.

1
  • I found the "*(Om[1])" command to be interesting. It quite literally did what I needed it to do via "open *(Om[1])". Though I think the best solution you mentioned is the tab completion. I just learned of the feature, and can see how it's would handle most situations where you don't want to type or paste a filename from current directory. Thanks for the detailed response! Commented Sep 2, 2022 at 4:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .